2010-02-22 17 views
0

我收到錯誤執行以下語句:IF如果以任一方式執行?

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

+0

謝謝你的編輯,不知道發生了什麼事!預覽是好的。 – 2010-02-22 16:33:43

回答

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 ('...') 
+0

更新:現在所有的表存在,我仍然得到同樣的錯誤! – 2010-02-22 16:28:45

+0

對不起,只是看了你的答案,讓我檢查一下吧 – 2010-02-22 16:29:19

+0

很酷,有用。謝謝 – 2010-02-22 16:34:25

相關問題