SQL中的事務

2021-04-23 03:55:39 字數 2020 閱讀 2474

sql中的事務

事務:begin transaction       開始事務

commit transaction 提交事務

rollboack transaction 回滾事務

set implicit_ransaction on    隱式事務

update customer set nickname-'nicky'

where customerid=10

這樣這條語句不會改變資料,必須在最後加上,commit transaction 才會提交上述事務.

因為我們指明使用隱式事務,所以每一條語句都會當成是乙個事務,所以要commit transaction才能提交.

事務完整性:違反事務完整性的問題有3類: 髒讀 (dirty read)、不可重複讀(nonrepeatable read)、幻影行(phantom rows)

解決這3個問題,需要在事務之間使用不同的完整性或者隔離級別。

髒讀:乙個事務讀取了另乙個事務尚未提交的更新,就叫做髒讀。

例:set transaction isolation level read committed   --設定事務不允許髒讀,可重複讀,可幻影行

--transaction 1    開啟查詢分析器,建立乙個連線,執行以下命令

use northwind

begin transaction

update customers

set companyname='transaction1'

where customerid='alfki'

commit transaction     --這個命令暫不執行,不讓這個事務提交

--transaction 2   在建立乙個連線,執行以下命令

use northwind

set transaction isolation level read uncommitted   --設定事務可以髒讀

select * from customers

where customerid='alfki'

這裡能夠成功讀取到事務1還沒有提交更改的資料,此時己經發生了髒讀

這裡執行以下命令

set transaction isolation level read committed   --設定事務不可以髒讀

select * from customers

where customerid='alfki'

這時出現延時現象,因為我們設的是不可髒讀。 此時將連線1 執行 commit transaction  發現連線2馬上顯示出了資料。

不可重複讀:如果事務二能夠看到事務一所提交的資料更新,就意味著出了不可重複讀型事務缺陷。

例:在以上建立的連線2中,執行以下命令

--transaction 2

set transaction isolation level repeatable read   --設定事務不可重複讀

begin transaction

select * from customers

where customerid='alfki'

select * from customers       標註:a

where customerid='alfki'

commit transaction

在以上建立的連線1中,執行以下命令,發現連線1出現延時現象,說明事務二無法更改同一條資料,在時在連線2中執行標註:a以下的命令,

因為連線1無法更改所以不會出現重複讀現象。 標註a:以下命令完成後,連線1更改資料成功。

--transaction 1

begin transaction

update customers

set companyname='non-repeatable111'

where customerid='alfki'

commit transaction

幻影行:當乙個事務的select語句返回的結果受到另乙個事務的影響而發生改變的現象叫做幻影行。

不做測試了。

SQL中事務的使用

事務的使用 select from mr upload manual excel where excel id m000181431 begin tran 開始事務 declare count int 宣告變數 set count 0 變數初始化 update mr upload manual ex...

SQL中事務隔離

use db3 insert into account name,balance values 張三 1000 李四 1000 張三轉500給李四 張三賬戶減500,李四加500,需要確保這些動作同時完成,不然會有損失 update account set balance 5000 1.張三轉賬50...

SQL中事務的隔離級別

sql server隔離 收藏 sql server隔離語句如下 set transaction isolation level read uncommitted read committed repeatable read snapshot serializable 一次只能設定乙個隔離級別選項,...