Sql server 如果执行任何一种方式?

Sql server 如果执行任何一种方式?,sql-server,tsql,sql-server-express,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

执行以下语句时出现错误:

 /* 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必须是批处理中的第一个表。 也就是说,你不能先以你现有的形式来检验存在

那么你就不能中途坚持做分批处理了

因此,动态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 ('...')

谢谢你的编辑,不知道发生了什么!预览还可以。