我试图半自动创建我的数据库 作为这一部分,我想添加列描述的扩展属性。 当我尝试在脚本中运行sp_sqlexec(或者甚至只是Exec(@mystring)时,出现错误,但是如果在调试时从监视窗口复制动态sql字符串,然后在复制的字符串上运行sp_sqlexec单独的窗口我没有得到任何错误和扩展属性正确添加 下面的脚本演示该问题:在SSMS复制的字符串与原始字符串有不同的行为
--Create a table to apply column descriptions to
Create table dbo.table1 (id int, name nvarchar(20));
--Create the table that contains our column descriptions
Create table dbo.column_descs_table (schemaname nvarchar(20), tablename nvarchar(20), columnname nvarchar(20), column_description nvarchar(20))
Insert into column_descs_table (schemaname, tablename, columnname, column_description)
values ('dbo', 'table1', 'id', 'the id column'), ('dbo' , 'table1', 'name', 'the name column');
--Dynamic sql string varaible to hold the commands
Declare @dyn_sql nvarchar(max);
Set @dyn_sql = 'N'''; --Set to opening quote
--now create the string containing commands to add column escriptions
SELECT @dyn_sql = @dyn_sql + N' EXEC sp_addextendedproperty ''''Col Desc'''', ''''' + column_description + N''''', ''''SCHEMA'''', ' + schemaname + N', ''''TABLE'''', ' + tablename + N', ''''COLUMN'''', ' + columnname + N' ;'
FROM dbo.column_descs_table
Set @dyn_sql = @dyn_sql + ''''; --add the closing quote
Print @dyn_sql --If I copy the contents of @dyn_sql here and run seperately it works OK
Exec sp_sqlexec @dyn_sql -- this line causes error
我得到的错误是 消息102,15级,状态1,行 附近有语法错误'EXEC sp_addextendedproperty '山口说明', 'id列', 'SCHEMA',DBO, 'TABLE',表1, '列',ID; EXEC sp_addextendedprope'。
然而,如果我单步执行代码并复制@dyn_sql的内容,则粘贴如下:
Exec sp_sqlexec N'EXEC sp_addextendedproperty''Col Desc''',''id'''',''SCHEMA' ',dbo,'TABLE',table1,''COLUMN'',id; EXEC sp_addextendedproperty''Col Desc'',''名称列'','SCHEMA',dbo,''TABLE'',table1,''COLUMN'',名称;'
然后,上述工作正常,并按预期添加列描述。
对这个特定的复制问题的任何帮助非常感谢。我明白使用动态SQL的安全问题(这个脚本会从数据库中删除一次我的设置完成)提前
感谢
裘德
sp_sqlexec在SQL Server 7假想删除,不再正式支持(http://technet.microsoft.com/en-us/library/cc917540.aspx)。我很惊讶它仍然存在于SQL2008R2中 - 在线文档早已不复存在。 – MartW
感谢您的建议。我将更改脚本以使用sp_executesql。 –