[英]Stored procedure: Variable table names
I want to make it easier to insert new default values to existing columns from my setup. 我想更容易从我的设置中向现有列插入新的默认值。 For better overview and less errors, I want to make a oneliner from a three-liner with redundant names.
为了更好地概述和减少错误,我想用一个带有冗余名称的三线制作一个oneliner。 My first attempt at a store dprocedure for that is:
我在商店dprocedure的第一次尝试是:
CREATE PROCEDURE InsertDefault
-- Add the parameters for the stored procedure here
@TableName VARCHAR(200),
@FieldName VARCHAR(200),
@DefaultValue VARCHAR(200)
AS
BEGIN
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(@TableName) AND name = @FieldName)
ALTER TABLE @TableName ADD @FieldName [int] CONSTRAINT CONCAT('DF_', @TableName, '_', @FieldName) DEFAULT @DefaultValue NOT NULL
GO
END
GO
But it seems that ALTER TABLE @TableName
does not work, nor does the concatenation for the constraint name. 但似乎
ALTER TABLE @TableName
不起作用,也没有约束名称的串联。
What am I missing here? 我在这里错过了什么?
And then, is there a possibility to make @DefaultValue
a mixed type? 然后,是否有可能使
@DefaultValue
成为混合类型?
You have to use dynamic sql (don't forget to escape single quotes in query string if they are present): 你必须使用动态sql(如果它们存在,不要忘记在查询字符串中转义单引号):
declare @cmd nvarchar(4000)
select @cmd = 'ALTER TABLE ' + @TableName + ' ADD ' + @FieldName
+ ' [int] CONSTRAINT ' + CONCAT('DF_', @TableName, '_', @FieldName)
+ ' DEFAULT ' + @DefaultValue + ' NOT NULL'
exec sp_executesql @cmd
Try this.... 试试这个....
BEGIN
IF NOT EXISTS (SELECT * FROM sys.columns WHERE object_id = OBJECT_ID(@TableName) AND name = @FieldName)
exec('ALTER TABLE ' + @TableName + 'ADD ' + @FieldName + ' [int] CONSTRAINT CONCAT(''DF_'', ' + @TableName + ','' _'', ' + @FieldName + ') DEFAULT ' + @DefaultValue + ' NOT NULL')
GO
END
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.