这是我在StackOverflow上的第一个问题,所以请很好;)
假设我有这样的触发器:
CREATE TRIGGER trigger1 ON [dbo].[table1] AFTER UPDATE AS BEGIN --declare some vars DECLARE @Col1 SMALLINT DECLARE @Col1 TINYINT --declare cursor DECLARE Cursor1 CURSOR FOR SELECT Col1,Col2 FROM INSERTED --do the job OPEN Cursor1 FETCH NEXT FROM Cursor1 INTO @Col1,@Col2 WHILE @@FETCH_STATUS = 0 BEGIN IF ...something... BEGIN EXEC myProc1 @param1 = @Col1,@Param2 = @Col2 END ELSE IF ...something else... BEGIN EXEC myProc2 @param1 = @Col1,@Param2 = @Col2 END FETCH NEXT FROM Cursor1 INTO @Col1,@Col2 END --clean it up CLOSE Cursor1 DEALLOCATE Cursor1 END
我想确保Cursor1始终关闭并释放。甚至myProc1或myProc2失败。
我使用try / catch块吗?
谢谢,
卡米尔
解决方法
是的,使用TRY / CATCH,但请确保您之后释放等等。
不幸的是,在sql Server中终于没有了。
不幸的是,在sql Server中终于没有了。
但是,我建议将其放在另一个try / catch中
CREATE TRIGGER trigger1 ON [dbo].[table1] AFTER UPDATE AS BEGIN --declare some vars DECLARE @Col1 SMALLINT,@Col1 TINYINT BEGIN TRY --declare cursor DECLARE Cursor1 CURSOR FOR SELECT Col1,Col2 FROM INSERTED --do the job OPEN Cursor1 FETCH NEXT FROM Cursor1 INTO @Col1,@Col2 WHILE @@FETCH_STATUS = 0 BEGIN IF ...something... EXEC myProc1 @param1 = @Col1,@Param2 = @Col2 ELSE IF ...something else... EXEC myProc2 @param1 = @Col1,@Param2 = @Col2 FETCH NEXT FROM Cursor1 INTO @Col1,@Col2 END END TRY BEGIN CATCH --do what you have to END CATCH BEGIN TRY --clean it up CLOSE Cursor1 DEALLOCATE Cursor1 END TRY BEGIN CATCH --do nothing END CATCH END
触发器中的光标是否是一个好主意是不同的事情…