我有以下T-SQL:
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;
解析后会出现此错误:
Msg 102,Level 15,State 1,Line 9
'FK_8bff7074914bc29885004c0a323'附近的语法不正确。
单独或仅在事务中时,没有解析错误。
答案 0 :(得分:1)
在GO
行
ALTER 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块,这样只执行该行如果一切顺利
答案 1 :(得分:0)
你不应该拥有Go
,因为它表示批次的结束,你的提交应该在alter table之后。
此外,没有必要检查一个事务是否在catch上运行,因为在这种情况下,它总是有
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