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

后端 未结 7 1938
日久生厌
日久生厌 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:25

    The AFTER INSERT trigger approach involves overhead due to the extra UPDATE statement. I suggest using an INSTEAD OF INSERT trigger, as follows:

    CREATE TRIGGER tablename_on_insert ON tablename 
    INSTEAD OF INSERT 
    AS
    INSERT INTO tablename (oldcolumn, newcolumn)
    SELECT oldcolumn, ISNULL(newcolumn, oldcolumn)
    FROM inserted
    

    This does not work though if the oldcolumn is an auto-identity column.

提交回复
热议问题