如何更改表中的计算列 [英] How to alter the computed column in a table

查看:46
本文介绍了如何更改表中的计算列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



我有一个包含两个计算列的表格。

Col1 as(Val1 + Val2)

Col2 as(Val3 + Val4)



结果如下:



Val1 Val2 Val3 Val4 Col1 Col2

-----------------------------

10 20 30 40 30 70



现在,要求是我想要将计算列的公式更改为

Col1 as(Val1 + Val3 )

Col2 as(Val2 + Val4)



但是这不应该改变以前的数据,它应该只改变新数据。



应该是这样的:



Val1 Val2 Val3 Val4 Col1 Col2

-------------------------------

10 20 30 40 30 70(现有数据 - 不应该改变)

1 2 3 4 4 6(应根据新公式更改数据)





提前致谢!



我拥有什么尝试过:



我试过用ALTER表做这件事

例如

ALTER TABLE TEMP

DROP COLUMN Col1



ALTER TABLE TEMP

添加栏目Col1为(Val1 + Val3)



但这也导致更改先前/现有值。

Hi All,

I have a table containing two computed columns.
Col1 as (Val1+Val2)
Col2 as (Val3+Val4)

it has result as:

Val1 Val2 Val3 Val4 Col1 Col2
-----------------------------
10 20 30 40 30 70

Now, the requirement is I want change the formula of the computed columns as
Col1 as (Val1+Val3)
Col2 as (Val2+Val4)

But having this should not change the previous data, it should only change the new data.

It should be like:

Val1 Val2 Val3 Val4 Col1 Col2
-------------------------------
10 20 30 40 30 70 (Existing data - should not change)
1 2 3 4 4 6 (should change the data according to the new formula )


Thanks in advance!

What I have tried:

I tried doing it using ALTER table
E.g
ALTER TABLE TEMP
DROP COLUMN Col1

ALTER TABLE TEMP
ADD COLUMN Col1 as (Val1+Val3)

But this is causing changing the previous/existing values as well.

推荐答案

您可以创建触发器而不是更改列



插入后只需更新列col1和col2



Val1 + Val3数据进入Col1

Val2 + Val4数据进入Col2





例如



You can create trigger instead of change columns

After insert just update column col1 and col2 respectivly

Val1 + Val3 data into Col1
Val2 + Val4 data into Col2


e.g.

CREATE TRIGGER TRIGGER_NAME ON dbo.TABLENAME
AFTER INSERT AS
DECLARE @REF_ID NVARCHAR(55);

SELECT @REF_ID=i.REF_ID FROM inserted i;

UPDATE TABLENAME SET COL1 = (VAL1 +VAL3),COL2 = (VAL2 +VAL4) WHERE REF_ID = @REF_ID

GO





注意:未经测试即可编写,您可能需要根据需要进行更改


这篇关于如何更改表中的计算列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆