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

后端 未结 7 1933
日久生厌
日久生厌 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: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])
    

提交回复
热议问题