Add a column to a table with a default value equal to the value of an existing column

后端 未结 7 1941
日久生厌
日久生厌 2020-12-05 03:41

How to add a column to a SQL Server table with a default value that is equal to value of an existing column?

I tried this T-SQL statement:

ALTER TABL         


        
7条回答
  •  陌清茗
    陌清茗 (楼主)
    2020-12-05 04:19

    I don't like them very much but here is how you could do this with an AFTER INSERT trigger:

    CREATE TRIGGER TableX_AfterInsert_TRG 
      ON TableX 
    AFTER INSERT
    AS
      UPDATE TableX AS t
      SET t.newcolumn = t.oldcolumn
      FROM Inserted AS i
      WHERE t.PK = i.PK ;              -- where PK is the PRIMARY KEY of the table   
    

提交回复
热议问题