[英]Incorrect syntax near ALTER NOCHECK CONSTRAINT - SQL Server 2008
I am trying to disable a table's constraint with an ALTER statement using BCP commands. 我正在尝试使用BCP命令使用ALTER语句禁用表的约束。 My code is as follows:
我的代码如下:
SET @disableConstraints = 'SQLCMD -E -S server-Name -d '+@databaseName+' -Q "EXEC sp_MSforeachtable @command1 = ALTER TABLE '+@schemaName+'.'+@tableName+' NOCHECK CONSTRAINT ALL;" >> Z:\Log\ErrorLog.txt'
However when I execute the xp_cmdshell
command, the ErrorLog.txt
will print an error saying: 但是,当我执行
xp_cmdshell
命令时, ErrorLog.txt
将显示一条错误消息:
Msg 156, Level 15, State 1, Server server-Name, Line 1
消息156,级别15,状态1,服务器服务器名称,第1行
Incorrect syntax near the keyword 'ALTER'.关键字“ ALTER”附近的语法不正确。
I've been fiddling around with single quotes and double quotes, but I am not getting anywhere. 我一直在摆弄单引号和双引号,但是我什么都没得到。
Can someone help spot the syntax error? 有人可以帮助您发现语法错误吗?
您在更改之前错过了双引号
SET @disableConstraints = 'SQLCMD -E -S server-Name -d ' + @databaseName + ' -Q EXEC sp_MSforeachtable @command1 = "ALTER TABLE ' + @schemaName + '.' + @tableName + ' NOCHECK CONSTRAINT ALL;" >> Z:\Log\ErrorLog.txt'
In you cursor use only this query: 在您的游标中,仅使用以下查询:
DECLARE @sql nvarchar(max);
DECLARE tables_cursor FOR...
OPEN tables_cursor;
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT QUOTENAME(@schemaName)+'.'+QUOTENAME(@tableName);
set @sql = 'ALTER TABLE '+QUOTENAME(@schemaName)+'.'+QUOTENAME(@tableName)+' NOCHECK CONSTRAINT ALL;';
EXEC sp_executesql @sql;
FETCH NEXT FROM tables_cursor INTO @schemaName, @tableName;
END
CLOSE tables_cursor;
DEALLOCATE tables_cursor;
If all is executed on the same server and database, you don't need to use sqlcmd and connect to another server. 如果所有操作均在同一服务器和数据库上执行,则无需使用sqlcmd并连接到另一台服务器。 Dynamic SQL with EXEC and sp_executesql will do it.
带有EXEC和sp_executesql的动态SQL将完成此操作。
在ALTER的开头和ALL的结尾需要两个单引号
SET @disableConstraints = 'SQLCMD -E -S server-Name -d '+@databaseName+' -Q "EXEC sp_MSforeachtable @command1 = ''ALTER TABLE '+@schemaName+'.'+@tableName+' NOCHECK CONSTRAINT ALL'';" >> Z:\Log\ErrorLog.txt'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.