开发者

Is IF Executed either way?

开发者 https://www.devze.com 2022-12-20 18:19 出处:网络
I am getting errors executing the following statement: /* AccountTypes Constraints */ IFEXISTS (SELECT 1 FROM sys.objects WHERE object_id = OBJECT_ID(N\'[dbo].[AccountTypes]\') AND type in (N\'U\')

I am getting errors executing the following statement:

 /* 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 */

the case is that the table [AccountTypes] really does not exist, but why am I getting errors while I am already checking if the table exist or not!!!!

following are the errors i am getting:开发者_Python百科

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


ALTER TABLE must be the first in the batch. That is, you can't test for existence first in the form you have.

Then you can't stick GO as batch separator halfway through.

So, dynamic 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 ('...')
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号