Sync two columns in the same table

时间:2016-04-04 17:54:13

标签: sql-server tsql

I have a table where, in the model, I had to rename one of the columns. I will have programs using the "first" model and other using the new, "second" model. (The transition between models will be gradual). So I decided to keep both columns:

Document
    creator
    coCreator   // old column
    creator2    // new column
    creator3    // another new column

I want to keep coCreator and creator2 synced, i.e. always with the same value. I'm confused with the trigger syntax on how to achieve this.

I'm using MS SQL Server.

Both columns are foreign keys. Will it have some unforseen problems?

Thanks in advance.

1 个答案:

答案 0 :(得分:0)

If you really want to do this I think it's better to not use a trigger. I think you can use a Computed column over here. See some more information: https://msdn.microsoft.com/en-us/library/ms188300.aspx

a COMPUTED column can't be a part of foreign key but that's not needed at all because creator2 can.

Example::

create table test (
ID int IDENTITY(1,1) PRIMARY KEY,
creator2 varchar(255) NULL,
coCreator AS (creator2) PERSISTED NULL
);

The PERSISTED means that the data will be saved on disk. Offcourse you need some kind of migration of you're existing table, but this should be quite easy.