我正在使用游标来删除一组表。我需要设置标志以确定所有交易是否成功。你能给我一些样例查询吗?
DEclare @intErrorCode int;
DECLARE @TblName NVARCHAR(MAX);
DECLARE TBL_Cursor CURSOR
FOR ( select name from sysobjects where name like 'tbl_flat%');
OPEN TBL_Cursor;
FETCH NEXT FROM TBL_Cursor INTO @TblName
WHILE (@@FETCH_STATUS <> -1)
BEGIN
IF LEN(@TblName) >0
BEGIN
DECLARE @strsql nvarchar(max)
BEGIN
something here
BEGIN TRAN
EXEC sp_executesql @strsql
COMMIT TRAN
SELECT @intErrorCode = @@ERROR
IF (@intErrorCode <> 0) GOTO PROBLEM
END
END
FETCH NEXT FROM TBL_Cursor INTO @TblName
END
CLOSE TBL_Cursor
DEALLOCATE TBL_Cursor
PROBLEM:
IF (@intErrorCode <> 0) BEGIN
PRINT 'Unexpected error occurred!'
END
答案 0 :(得分:1)
BEGIN TRY
BEGIN TRANSACTION
--your code
EXEC sp_executesql @strsql
COMMIT TRAN -- Transaction Success!
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK TRAN --RollBack in case of Error
-- you can Raise ERROR with RAISEERROR() Statement including the details of the exception
RAISERROR(ERROR_MESSAGE(), ERROR_SEVERITY(), 1)
END CATCH