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

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

    Try this:

    ALTER TABLE tablename ADD newcolumn type NOT NULL DEFAULT (0)
    Go
    Update tablename SET newcolumn = oldcolumn Where newcolumn = 0
    Go
    
    0 讨论(0)
  • 2020-12-05 04:10

    To extend Kapil's answer, and avoid the unwanted default constraint, try this:

    ALTER TABLE tablename ADD newcolumn type NOT NULL CONSTRAINT DF_TMP_TABLENAME_NEWCOLUMN DEFAULT -9999
    Go
    Update tablename SET newcolumn = oldcolumn
    Go
    ALTER TABLE tablename DROP CONSTRAINT DF_TMP_TABLENAME_NEWCOLUMN
    Go
    

    Replace -9999 by 'noData' if your type is varchar, nvarchar, datetime,... or by any compatible data for other types: specific value doesn't matter, it will be wiped by the 2nd instruction.

    0 讨论(0)
  • 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   
    
    0 讨论(0)
  • 2020-12-05 04:21

    For my case, I want to add a new not null unique column named CODE but I don't know about the value at the creation time. I set the default value for it by get a default value from NewID() then update later.

    ALTER TABLE [WIDGET] ADD [CODE] CHAR(5) NOT NULL DEFAULT(SUBSTRING(CONVERT(CHAR(36), NEWID()), 1, 5))
    
    ALTER TABLE [dbo].[WIDGET] WITH CHECK ADD CONSTRAINT [UQ_WIDGET_CODE] UNIQUE ([CODE])
    
    0 讨论(0)
  • 2020-12-05 04:21

    I think it will work if you use Set Identity_Insert <TableName> OFF and after the insert Statement that you wrote just use Set Identity_Insert <TableName> ON.

    0 讨论(0)
  • 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.

    0 讨论(0)
提交回复
热议问题