Alter Table Add Column and update the new Column in the same conditional IF statement(在同一条件 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?
推荐答案
您遇到了解析整个语句的问题,并且由于 Code
列尚不存在而导致 DML 失败.你现在有冲突:
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 语句中更改表添加列并更新新列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:在同一条件 IF 语句中更改表添加列并更新新列


- 在SQL中,如何为每个组选择前2行 2021-01-01
- 导入具有可变标题的 Excel 文件 2021-01-01
- 以一个值为轴心,但将一行上的数据按另一行分组? 2022-01-01
- 远程 mySQL 连接抛出“无法使用旧的不安全身份验证连接到 MySQL 4.1+"来自 XAMPP 的错误 2022-01-01
- 使用 Oracle PL/SQL developer 生成测试数据 2021-01-01
- SQL 临时表问题 2022-01-01
- 更改自动增量起始编号? 2021-01-01
- 如何将 SonarQube 6.7 从 MySQL 迁移到 postgresql 2022-01-01
- 如何使用 pip 安装 Python MySQLdb 模块? 2021-01-01
- 如何将 Byte[] 插入 SQL Server VARBINARY 列 2021-01-01