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

SqlSql Server-2008

Sql Problem Overview


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 TABLE tablename 
ADD newcolumn type NOT NULL DEFAULT (oldcolumn) 

but it's giving an error:

> The name "oldcolumn" is not permitted in this context. Valid > expressions are constants, constant expressions, and (in some > contexts) variables. Column names are not permitted.

Sql Solutions


Solution 1 - Sql

Try this:

ALTER TABLE tablename ADD newcolumn type NOT NULL DEFAULT (0)
Go
Update tablename SET newcolumn = oldcolumn Where newcolumn = 0
Go

Solution 2 - Sql

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.

Solution 3 - Sql

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   

Solution 4 - Sql

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.

Solution 5 - Sql

You can use computed column to insert new column in a table based on an existing column value

ALTER TABLE dbo.TableName ADD NewColumn AS (OldColumn) PERSISTED;

OR, if you want to make some changes to the value based on existing column value, use

ALTER TABLE dbo.TableName ADD NewColumn AS (OldColumn * 1.5) PERSISTED;

Solution 6 - Sql

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])

Solution 7 - Sql

Use a computed column, which will even work with IDENTITY column values:

CREATE TABLE #This
( Id	    INT IDENTITY(1,1)
 ,MyName	VARCHAR(10)
 ,FullName	AS (Myname + CONVERT(VARCHAR(10),Id)) PERSISTED);

INSERT #This VALUES ('Item'),('Item');

SELECT * FROM #This;

DROP TABLE #This;

yields the following:

Results as Grid

Solution 8 - Sql

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondoesdosView Question on Stackoverflow
Solution 1 - SqlKapil KhandelwalView Answer on Stackoverflow
Solution 2 - SqlHerman KanView Answer on Stackoverflow
Solution 3 - SqlypercubeᵀᴹView Answer on Stackoverflow
Solution 4 - SqlFrédéric ChauvièreView Answer on Stackoverflow
Solution 5 - SqlVijaiView Answer on Stackoverflow
Solution 6 - SqlTrần Thanh PhongView Answer on Stackoverflow
Solution 7 - SqlHigh Plains GrifterView Answer on Stackoverflow
Solution 8 - Sqluser7040891View Answer on Stackoverflow