我有一个简单的 TRY CATCH,在下面的查询中嵌入了 TRANSACTION。
我在查询中输入了错误的列名:ItemID1
在运行查询时的第二个UPDATE
中TRANSACTION
,我收到以下严重性高于 10 的错误消息:
消息 207,级别 16,状态 1,第 xxx 行无效的列名称“ItemID1”。
第一次UPDATE
成功运行(我希望它会ROLLBACK
)。
这表明它从未进入CATCH
区块。
根据我的理解,CATCH
捕获了 10 以上严重性的错误。这个是严重性 16,因此它应该已经捕获了它。任何想法为什么CATCH
从未被执行?
BEGIN TRY
IF OBJECT_ID('tempdb..#MyTempTable') IS NOT NULL
DROP TABLE #MyTempTable
CREATE TABLE #MyTempTable
(
ObjectID UNIQUEIDENTIFIER , OrgID NVARCHAR(20)
)
INSERT INTO #MyTempTable
SELECT ObjectTable1.ObjectID AS ObjectID ,OrgID
FROM ObjectTable1 WITH ( NOLOCK ) INNER JOIN Org WITH ( NOLOCK ) ON ObjectTable1.OrgID = Org.OrgID
WHERE OrgID IN ('Blah1', 'Blah2')
INSERT INTO #MyTempTable
SELECT ObjectTable2.ObjectID AS ObjectID, OrgID
FROM ObjectTable2 WITH ( NOLOCK ) INNER JOIN Org WITH ( NOLOCK ) ON ObjectTable2.OrgID = Org.OrgID
WHERE OrgID IN ('Blah3', 'Blah4')
SELECT * FROM #MyTempTable
BEGIN TRANSACTION
UPDATE ObjectTable1
SET ItemID = NULL FROM ObjectTable1 INNER JOIN #MyTempTable ON #MyTempTable.ObjectID = ObjectTable1.ObjectID
PRINT 'Updated ' + CAST(@@ROWCOUNT AS VARCHAR(20)) + ' Objects in ObjectTable1'
UPDATE ObjectTable2
SET ItemID = (ItemID1 + 1) FROM ObjectTable2 INNER JOIN #MyTempTable ON #MyTempTable.ObjectID = ObjectTable2.ObjectID
PRINT 'Updated ' + CAST(@@ROWCOUNT AS VARCHAR(20)) + ' Objects in ObjectTable2'
COMMIT
DROP TABLE #MyTempTable
END TRY
BEGIN CATCH
IF @@TRANCOUNT > 0
ROLLBACK
DROP TABLE #MyTempTable
DECLARE @ErrMsg NVARCHAR(4000) ,
@ErrSeverity INT
SELECT @ErrMsg = ERROR_MESSAGE() ,
@ErrSeverity = ERROR_SEVERITY()
RAISERROR(@ErrMsg, @ErrSeverity, 1)
END CATCH