我有一個場景,我需要運行多個插入,但最后只保存對資料庫的更改。如果任何插入發生任何例外,則不應保存先前的插入。這就像全有或全無的交易。
我知道我們可以使用物體框架來實作這一點,方法是在 foreach 插入回圈之外呼叫 _context.SaveChanges()。但是,是否有任何選項可以使用本機 SQL 查詢輕松完成此操作?
我正在處理的這個現有專案沒有物體框架設定。所以,在我將物體框架添加到這個專案之前,我只想知道是否有其他簡單的選項可以解決這個問題。謝謝!
uj5u.com熱心網友回復:
在 SQL 存盤程序中,假設使用 SQL 服務器:
--@insertdata could be of type xml or json depending on your version
--of sql server and use it to do all inserts
--in any case, you can set as many parameters as you need to do the work
@insertdata xml = null
Begin Try
--Begin Tran
BEGIN TRAN
--Do INSERTS
--Commit the Transaction
COMMIT TRAN
End Try
BEGIN Catch
--If we have an exception
IF @@TRANCOUNT > 0 ROLLBACK;
--Return the ErrorMessage
SELECT ERROR_MESSAGE()
--OR as suggested, THROW so the exception is raised
--THROW
END Catch
uj5u.com熱心網友回復:
你正在尋找的是Transactions,
“事務是在資料庫中執行單個活動或多個活動的邏輯作業單元。事務可能由單個讀取、寫入、洗掉或更新操作或這些操作的組合組成。”
在這里 和這里了解更多
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/408470.html
標籤:
上一篇:SQLBOM樹連接
