2012-05-17 70 views
0

我有下面的T-SQL:語法錯誤與TRY內DROP CONSTRAINT/CATCH

USE [MYDB] 
GO 
SET XACT_ABORT, NOCOUNT ON 
GO 
BEGIN TRANSACTION; 
BEGIN TRY 
     ALTER TABLE [dbo].[ContactRole] 
     DROP CONSTRAINT [FK_8bff7074914bc29885004c0a323] 
     GO 
END TRY 
BEGIN CATCH 
    SELECT 
     ERROR_NUMBER() AS ErrorNumber ,ERROR_SEVERITY() AS ErrorSeverity 
     ,ERROR_STATE() AS ErrorState ,ERROR_PROCEDURE() AS ErrorProcedure 
     ,ERROR_LINE() AS ErrorLine ,ERROR_MESSAGE() AS ErrorMessage; 

    IF @@TRANCOUNT > 0 
     ROLLBACK TRANSACTION; 
END CATCH 

IF @@TRANCOUNT > 0 
    COMMIT TRANSACTION; 

解析的時候,給了我這個錯誤:

消息102,15級,狀態1,第9行
「FK_8bff7074914bc29885004c0a323」附近的語法不正確。

當單獨或者只在一個事務中,沒有解析錯誤。

回答

1

GOALTER TABLE ... DROP CONSTRAINT ..行之後

.... 
BEGIN TRANSACTION; 
BEGIN TRY 
    ALTER TABLE [dbo].[ContactRole] 
    DROP CONSTRAINT [FK_8bff7074914bc29885004c0a323] 

    COMMIT TRANSACTION; 
END TRY 
BEGIN CATCH 
    SELECT 
     ERROR_NUMBER() AS ErrorNumber ,ERROR_SEVERITY() AS ErrorSeverity 
     ,ERROR_STATE() AS ErrorState ,ERROR_PROCEDURE() AS ErrorProcedure 
     ,ERROR_LINE() AS ErrorLine ,ERROR_MESSAGE() AS ErrorMessage; 

    IF @@TRANCOUNT > 0 
     ROLLBACK TRANSACTION; 
END CATCH 

GO一個SQL關鍵字 - 它只能通過SQL Server Management Studio中理解爲 「批處理分隔符」。

另外:把你的COMMIT TRANSACTION聲明ALTER TABLE命令後正確的 - 畢竟,如果確實存在錯誤 - 在代碼執行就會跳入catch塊向右走,所以如果一切正常這條線時,纔會執行

0

你不應該有Go,因爲它表明批處理結束,你的提交應該在alter table後面。

也沒有必要來檢查,如果交易在抓,因爲在這種情況下運行時,它總會有

USE [MYDB] 
GO 
SET XACT_ABORT, NOCOUNT ON 
GO 
BEGIN TRANSACTION; 
BEGIN TRY 
     ALTER TABLE [dbo].[ContactRole] 
     DROP CONSTRAINT [FK_8bff7074914bc29885004c0a323] 

     COMMIT TRANSACTION; 
END TRY 
BEGIN CATCH 
    SELECT 
     ERROR_NUMBER() AS ErrorNumber ,ERROR_SEVERITY() AS ErrorSeverity 
     ,ERROR_STATE() AS ErrorState ,ERROR_PROCEDURE() AS ErrorProcedure 
     ,ERROR_LINE() AS ErrorLine ,ERROR_MESSAGE() AS ErrorMessage; 

     ROLLBACK TRANSACTION; 
END CATCH