更改表添加列并在同一条件 IF 语句中更新新列 [英] Alter Table Add Column and update the new Column in the same conditional IF statement

查看:32
本文介绍了更改表添加列并在同一条件 IF 语句中更新新列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to add column and update it in the same if statement:

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

它抛出一个错误:

无效的列名代码"

有没有办法在一个事务中完成这些操作?

Is there any ways how to do these operations in one transaction?

推荐答案

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

You are running into the issue whereby the entire statement is parsed, and the DML fails because the Code column doesn't exist yet. You now have the conflict:

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

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

You'll need to find another way to retain the state of 'Add Code' logic across multiple statement batches, e.g. use a #temp table:

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

这篇关于更改表添加列并在同一条件 IF 语句中更新新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆