Test Column exists, Add Column, and Update Column

前端 未结 5 1722
一整个雨季
一整个雨季 2020-12-28 13:03

I\'m trying to write a SQL Server database update script. I want to test for the existence of a column in a table, then if it doesn\'t exist add the column with a default va

5条回答
  •  梦毁少年i
    2020-12-28 13:51

    I have often been annoyed by this problem myself, and unfortunately the solution suggested in Aaronaught's answer quickly becomes messy when @parameters and 'strings' are involved. However, I have found a different workaround by exploiting the usage of synonyms:

    IF(COL_LENGTH('MyTable', 'NewCol') IS NULL)
    BEGIN
        ALTER TABLE MyTable ADD NewCol VARCHAR(16) NULL;
    
        CREATE SYNONYM hack FOR MyTable;
        UPDATE hack SET NewCol = 'Hello ' + OldCol;
        DROP SYNONYM hack;
    
        ALTER TABLE MyTable ALTER COLUMN NewCol VARCHAR(16) NOT NULL;
    END
    

提交回复
热议问题