更改表添加列并在同一条件IF语句中更新新列

时间:2014-12-11 14:10:49

标签: sql sql-server sql-update

我正在尝试添加列并在同一个if语句中更新它:

BEGIN TRAN

IF NOT EXISTS(SELECT 1 FROM sys.columns 
              WHERE Name = N'Code' 
              AND Object_ID = Object_ID(N'TestTable'))
BEGIN
    ALTER TABLE TestTable 
    ADD Code NVARCHAR(10)

    UPDATE TestTable 
    SET Code = Name 
    WHERE 1=1
END

COMMIT

它会抛出错误:

  

无效的列名称“代码”

有没有办法在一次交易中如何进行这些操作?

4 个答案:

答案 0 :(得分:1)

您可以使用EXEC语句来完成此任务。

BEGIN TRAN

IF NOT EXISTS(SELECT 1 from sys.columns where Name = N'Code' and Object_ID = Object_ID(N'TestTable'))
BEGIN
    ALTER TABLE TestTable ADD Code NVARCHAR(10)

    Exec ('UPDATE TestTable SET Code = Name WHERE 1=1')
END

COMMIT

这是我使用的测试代码。

Create Table TestTable(Id Int, Name VarChar(20))

Insert Into TestTable Values(1,'George')

BEGIN TRAN

IF NOT EXISTS(SELECT 1 from sys.columns where Name = N'Code' and Object_ID = Object_ID(N'TestTable'))
BEGIN
    ALTER TABLE TestTable ADD Code NVARCHAR(10)

    Exec ('UPDATE TestTable SET Code = Name WHERE 1=1')
END

COMMIT

Select * From TestTable

Drop Table TestTable

答案 1 :(得分:1)

您正在遇到解析整个语句的问题,并且DML失败,因为Code列尚未存在。你现在有冲突:

  • ALTER TABLE需要GO(批量执行)
  • 您的多行批处理逻辑需要BEGIN / END包装器

您需要找到另一种方法来保留“添加代码”的状态。跨多个语句批次的逻辑,例如使用#temp表:

CREATE TABLE #tmpFlag(AddCode BIT);

IF NOT EXISTS(SELECT 1 from sys.columns where Name = N'Code' and Object_ID = Object_ID(N'TestTable'))
BEGIN
    INSERT INTO #tmpFlag VALUES(1);
    ALTER TABLE TestTable ADD Code NVARCHAR(10);
END;
GO

IF EXISTS (SELECT * FROM #tmpFlag)
BEGIN
   UPDATE TestTable SET Code = Name;
END;

DROP TABLE #tmpFlag;

SqlFiddle here

答案 2 :(得分:0)

试试这个,请参阅SQL Server 2008中的实例 enter image description here

BEGIN TRAN

    IF NOT EXISTS(SELECT 1 from sys.columns where Name = N'Code' and Object_ID = Object_ID(N'TestTable'))
    BEGIN
        ALTER TABLE TestTable ADD Code NVARCHAR(10)
        Go
        SET XACT_ABORT ON
        Go
        UPDATE TestTable SET Code = Name WHERE 1=1
    END

    COMMIT

答案 3 :(得分:0)

begin tranALTER以来,您不需要UPDATE; TRANSACTIONIF NOT EXISTS(SELECT 1 FROM sys.columns WHERE Name = N'Code' AND Object_ID = Object_ID(N'TestTable')) BEGIN BEGIN ALTER TABLE TestTable ADD Code NVARCHAR(10) END GO BEGIN UPDATE TestTable SET Code = Name WHERE 1=1 END GO END

{{1}}