IF是以哪种方式执行的?

时间:2010-02-22 15:47:52

标签: sql-server tsql sql-server-express

执行以下语句时出错:

 /* AccountTypes Constraints */
 IF  EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[AccountTypes]') AND type in (N'U'))
 BEGIN
  PRINT 'Table [AccountTypes] exist.'

  IF NOT EXISTS(SELECT 1 FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Accounts_AccountTypes]') AND parent_object_id = OBJECT_ID(N'[dbo].[Accounts]'))
  BEGIN
   ALTER TABLE [dbo].[Accounts]  WITH NOCHECK ADD  CONSTRAINT [FK_Accounts_AccountTypes] FOREIGN KEY([AccountType])
   REFERENCES [dbo].[AccountTypes] ([AccountTypeID])
   GO
   ALTER TABLE [dbo].[Accounts] CHECK CONSTRAINT [FK_Accounts_AccountTypes]
   GO 
  END
 END
 ELSE
  PRINT 'Table [AccountTypes] Does not exist to create [FK_Accounts_AccountTypes].'
 /* END: AccountTypes Constraints */

案例是表[AccountTypes]确实不存在,但是为什么我在检查表是否存在时遇到错误!!!!

以下是我得到的错误:

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

Msg 4917, Level 16, State 0, Line 1
Constraint 'FK_Accounts_AccountTypes' does not exist.

Msg 4916, Level 16, State 0, Line 1
Could not enable or disable the constraint. See previous errors.

Msg 156, Level 15, State 1, Line 2
Incorrect syntax near the keyword 'END'.

SQL 2005 Express

1 个答案:

答案 0 :(得分:2)

ALTER TABLE必须是批次中的第一个。 也就是说,你不能先以你的形式测试存在。

然后你不能将GO作为批量分隔符中途粘贴。

所以,动态SQL:

 /* AccountTypes Constraints */
 IF  EXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[AccountTypes]') AND type in (N'U'))
 BEGIN
  PRINT 'Table [AccountTypes] exist.'

  IF NOT EXISTS(SELECT 1 FROM sys.foreign_keys WHERE object_id = OBJECT_ID(N'[dbo].[FK_Accounts_AccountTypes]') AND parent_object_id = OBJECT_ID(N'[dbo].[Accounts]'))
  BEGIN
   EXEC ('ALTER TABLE [dbo].[Accounts]  WITH NOCHECK ADD  CONSTRAINT [FK_Accounts_AccountTypes] FOREIGN KEY([AccountType])
   REFERENCES [dbo].[AccountTypes] ([AccountTypeID])')
   EXEC ('...')