当前位置: 首页 > 图文教程 > 数据库 > MSSQL > SQLServer2005 的查询独占模拟

MSSQL
SQLServer数据库和Access数据库的各自特点
SQLite数据库最适合做网站内容管理系统(CMS)
彻查SQL Server数据库查询速度慢
BUILTIN\Administrators登陆账号
PHP简单学习,保证入门学会
网站主机教程(7):网站主机的数据库技术
SQL入门:SQL Server 2000企业版安装
SQL入门:MSDE 2000无人职守自动安装
如何连接注册远程SQL Server数据库
提高SQL Server安装安全性要做的10件事
SQL Server连接体系结构的客户端
为SQL Server提供更多的内存
检测SQL Server数据库服务器异常现象
SQL Server入门教程(1):SQL简介和SQL语法
SQL Server入门教程(2):Select和DISTINCT语句
SQL2008新特性Resource Governor
教你配置安全稳定的SQL Server数据库
SQL Server教程:学习SELECT
如何替换SQL Server数据库内容
Sql-Server应用程序的高级Sql注入

MSSQL 中的 SQLServer2005 的查询独占模拟


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-09-13   浏览: 99 ::
收藏到网摘: n/a

这个问题一直被很多人关注,基本上得到的答案是两种倾向,一种是锁一种是给记录打标记(也就是update)。 对于应用来说,我并不提倡人为给记录加锁,这样会惹来很多麻烦,况且锁并不能解决所有问题,如果你有这方面好的经验我们可以进一步交流。
对于应用来说,我并不提倡人为给记录加锁,这样会惹来很多麻烦,况且锁并不能解决所有问题,如果你有这方面好的经验我们可以进一步交流。
复制代码 代码如下:

set nocount on
use tempdb
go
if (object_id ('tb' ) is not null )
drop table tb
go
create table tb (id int identity (1 , 1 ), name varchar (10 ), tag int default 0 )
insert into tb (name ) select 'a'
insert into tb (name ) select 'b'
insert into tb (name ) select 'c'
insert into tb (name ) select 'd'
insert into tb (name ) select 'e'
go
update top (2 ) tb with (rowlock , readpast ) set tag = 1 output inserted . id , inserted . name where tag = 0
go
update top (2 ) tb with (rowlock , readpast ) set tag = 1 output inserted . id , inserted . name where tag = 0
go
update top (2 ) tb with (rowlock , readpast ) set tag = 1 output inserted . id , inserted . name where tag = 0
go
set nocount off
/*
id name
----------- ----------
1 a
2 b
id name
----------- ----------
3 c
4 d
id name
----------- ----------
5 e
*/

如果你有更好的建议,我们不妨探讨一下。