views:

77

answers:

1

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:

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

+2  A: 

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 ('...')
gbn
UPDATE: now all tables exist and i am still getting the same error !!!
Basel Nimer
sorry, just read your answer, let me check it please
Basel Nimer
Cool, it works. thanks
Basel Nimer