0

我正在尝试执行以下 SQL:

declare @newLine as varchar(1) = char(13);
declare @sqlCmd as varchar(max) = '';
SELECT @sqlCmd = @sqlCmd + 'alter table ' + OBJECT_NAME(parent_object_id) + ' drop constraint ' + OBJECT_NAME(OBJECT_ID) + ';' + @newLine
FROM sys.objects
WHERE type_desc LIKE '%CONSTRAINT'
order by case when left(OBJECT_NAME(OBJECT_ID),2) = 'PK' then 1 else 0 end
exec (@sqlCmd)

但是,这给了我以下错误消息:

Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '.'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '.'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '.'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '.'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '.'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '.'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '.'.
Msg 102, Level 15, State 1, Line 1
Incorrect syntax near '.'.

有人可以给我一些关于为什么会出现消息的建议。据我所知,这个脚本以前有效,但现在无效。

当我没有选择进入字符串时,输出如下所示:

alter table Answer drop constraint FK_dbo.Answer_dbo.Question_QuestionId;
alter table Question drop constraint FK_dbo.Question_dbo.Problem_ProblemId;
alter table Question drop constraint FK_dbo.Question_dbo.QuestionStatus_QuestionStatusId;
alter table Problem drop constraint FK_dbo.Problem_dbo.Reference_ReferenceId;

这是用于创建的代码:

ALTER TABLE [dbo].[Answer]  WITH CHECK ADD  CONSTRAINT [FK_dbo.Answer_dbo.Question_QuestionId] FOREIGN KEY([QuestionId])
REFERENCES [dbo].[Question] ([QuestionId])
4

1 回答 1

3

您需要将约束名称包装在[]

declare @newLine as varchar(1) = char(13);
declare @sqlCmd as varchar(max) = '';
SELECT @sqlCmd = @sqlCmd + 'alter table ' + OBJECT_NAME(parent_object_id) + ' drop constraint [' + OBJECT_NAME(OBJECT_ID) + '];' + @newLine
FROM sys.objects
WHERE type_desc LIKE '%CONSTRAINT'
order by case when left(OBJECT_NAME(OBJECT_ID),2) = 'PK' then 1 else 0 end
exec (@sqlCmd)
于 2013-09-29T08:58:45.107 回答