zoukankan      html  css  js  c++  java
  • sql server行级锁,排它锁,共享锁的使用

    1 如何锁一个表的某一行

    SET TRANSACTION ISOLATION LEVEL READ UNCOMMITTED

    SELECT * FROM table ROWLOCK WHERE id = 1

    2 锁定数据库的一个表

    SELECT * FROM table WITH (HOLDLOCK)

    加锁语句:
    sybase:
    update 表 set col1=col1 where 1=0 ;
    MSSQL:
    select col1 from 表 (tablockx) where 1=0 ;
    oracle:
    LOCK TABLE 表 IN EXCLUSIVE MODE ;
    加锁后其它人不可操作,直到加锁用户解锁,用commit或rollback解锁


    几个例子帮助大家加深印象
    设table1(A,B,C)
    A B C
    a1 b1 c1
    a2 b2 c2
    a3 b3 c3

    1)排它锁
    新建两个连接
    在第一个连接中执行以下语句
    begin tran
    update table1
    set A='aa'
    where B='b2'
    waitfor delay '00:00:30' --等待30秒
    commit tran
    在第二个连接中执行以下语句
    begin tran
    select * from table1
    where B='b2'
    commit tran

    若同时执行上述两个语句,则select查询必须等待update执行完毕才能执行即要等待30秒

    2)共享锁
    在第一个连接中执行以下语句
    begin tran
    select * from table1 holdlock -holdlock人为加锁
    where B='b2'
    waitfor delay '00:00:30' --等待30秒
    commit tran

    在第二个连接中执行以下语句
    begin tran
    select A,C from table1
    where B='b2'
    update table1
    set A='aa'
    where B='b2'
    commit tran

    若同时执行上述两个语句,则第二个连接中的select查询可以执行
    而update必须等待第一个事务释放共享锁转为排它锁后才能执行 即要等待30秒

    3)死锁
    增设table2(D,E)
    D E
    d1 e1
    d2 e2
    在第一个连接中执行以下语句
    begin tran
    update table1
    set A='aa'
    where B='b2'
    waitfor delay '00:00:30'
    update table2
    set D='d5'
    where E='e1'
    commit tran

    在第二个连接中执行以下语句
    begin tran
    update table2
    set D='d5'
    where E='e1'
    waitfor delay '00:00:10'
    update table1
    set A='aa'
    where B='b2'
    commit tran
  • 相关阅读:
    简单的jquery左侧导航栏和页面选中
    SQL 无限级分类语句
    创建第一个MVC专案--初识MVC
    powershell读写磁盘变量(对象序列化)
    powershell字符界面的,powershell加WPF界面的,2048游戏
    Invoke-WebRequest Invoke-RestMethod 乱码研究
    powershell中的两只爬虫
    powershell脚本闪电输入神器
    请把不听话的【return】关进【class】这个笼子
    当powershell遇上mysql引发的血案
  • 原文地址:https://www.cnblogs.com/cnlmjer/p/4099865.html
Copyright © 2011-2022 走看看