2
我正在使用下面的SQL來刪除記錄並插入到事務內的Customers表中。如果插入語句中有錯誤,則顯示錯誤消息,當我嘗試執行select * from customers
時,它不顯示結果集。當我關閉SSMS窗口時,它顯示There are uncommitted transactions. Do you wish to commit these transactions before closing the window?
SQL事務處理不起作用
當我單擊確定後,結果從表中顯示出來。那麼,在使用交易時是否有任何鎖定機制發生?
USE CMSDB;
BEGIN TRY
BEGIN TRAN t1;
DELETE FROM Customers
print @@trancount -->prints 3 since there are three records
INSERT INTO CUSTOMERS
INSERT INTO CUSTOMERd --> error here
INSERT INTO CUSTOMERS
COMMIT TRAN t1;
END TRY
BEGIN CATCH
print 'hi' --> not printing
select @@trancount --> not resulting anything
IF @@TRANCOUNT > 0
ROLLBACK TRAN t1;
-- Error Message
DECLARE @Err nvarchar(1000)
SET @Err = ERROR_MESSAGE()
RAISERROR (@Err,16,1)
END CATCH
GO
消息
(3 row(s) affected)
(1 row(s) affected)
(1 row(s) affected)
(1 row(s) affected)
Msg 208, Level 16, State 1, Line 8
Invalid object name 'dbo.Customerd'.
聽起來就像在某個時間點(在運行這最後一批之前),您只使用'BEGIN TRANSACTION;'突出顯示代碼。 「SELECT @@ TRANCOUNT;」是什麼意思? –
似乎它由於某種原因未進入捕獲。我嘗試在catch中打印@@ trancount,但不能。 – Sunny
只是'SELECT @@ TRANCOUNT;'在它自己。再次,我認爲你至少執行了一個'BEGIN TRANSACTION;'而沒有提交或回滾。 –