[英]Add column to existing table and default value to another column without dynamic sql
For Sql Server 2005 and 2008 I want to check if a column already exists on a given table and create it if it doesn't. 对于Sql Server 2005和2008,我想检查给定表上是否已存在一列,如果不存在则创建它。 This new column should have a default value of an ExistingColumn.
此新列的默认值应为ExistingColumn。 Currently I need to use dynamic sql to fill the new column because sql server will complain of a syntax error.
当前,我需要使用动态sql来填充新列,因为sql server将抱怨语法错误。
Here is the current sql server code: 这是当前的sql服务器代码:
IF NOT EXISTS (SELECT TOP 1 1 FROM sys.columns WHERE [name] = N'NewColumn' AND OBJECT_ID = OBJECT_ID(N'ExistingTable'))
BEGIN
ALTER TABLE [dbo].[ExistingTable] ADD [NewColumn] VARCHAR(50) NULL;
exec sp_executesql N'UPDATE [dbo].[ExistingTable] SET NewColumn = ExistingColumn'
ALTER TABLE [dbo].[ExistingTable] ALTER COLUMN [NewColumn] VARCHAR(50) NOT NULL
END
GO
Is there any other way to solve this problem without resorting to dynamic sql? 是否有其他方法可以解决此问题而无需借助动态sql?
SQL Server is parsing your statement before your ALTER
runs, and saying "Hey, no such column." SQL Server正在
ALTER
运行之前解析您的语句,并说“嘿,没有这样的列”。 The parser doesn't understand IF
and other branching and can't follow the sequence of events when you mix DDL and DML - or predict the sequence the events will take and what branching will happen at runtime. 解析器不了解
IF
和其他分支,并且在混合DDL和DML时无法遵循事件的顺序-或预测事件将采取的顺序以及运行时将发生什么分支。
Deferred name resolution allows you to access objects that don't exist yet, but not columns that don't exist yet on objects that do. 延迟名称解析允许您访问尚不存在的对象 ,但可以访问尚不存在的对象上的列 。
So, dynamic SQL seems like the way you'll have to do it. 因此,动态SQL似乎是您必须执行的方式。
Since you're creating the column regardless, you could do two separate batches. 由于无论如何创建列,都可以进行两个单独的批处理。
IF NOT EXISTS (SELECT TOP 1 1 FROM sys.columns WHERE [name] = N'NewColumn' AND OBJECT_ID = OBJECT_ID(N'ExistingTable'))
BEGIN
ALTER TABLE [dbo].[ExistingTable] ADD [NewColumn] VARCHAR(50) NULL;
END
GO
IF EXISTS (SELECT TOP 1 1 FROM sys.columns WHERE [name] = N'NewColumn' AND OBJECT_ID = OBJECT_ID(N'ExistingTable'))
BEGIN
IF EXISTS (SELECT 1 FROM [dbo].[ExistingTable] WHERE NewColumn IS NULL)
BEGIN
UPDATE [dbo].[ExistingTable] SET NewColumn = ExistingColumn
ALTER TABLE [dbo].[ExistingTable] ALTER COLUMN [NewColumn] VARCHAR(50) NOT NULL
END
END
GO
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.