注册 | 登录 |
地方论坛门户及新闻和人才网址大全

解析SQLServer2005的Top功能

时间:2021-07-21人气:-


所有人都知道select top 的用法,但很多人还不知道update top 和 delete top 怎么用。以往的做法是set rowcount来指定,其实SQL2005中对于Top语句的增强除了参数化之外还包括对update和delete的支持,但可惜的是还不支持自定义的order by列。如果要自定义派序列可以借助CTE.对于CTE的任何更改都会影响到原始表。
我们看下面的测试代码。

复制代码 代码如下:


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'
/*--更新前两行
idnametag
----------- ---------- -----------
1a1
2b1
3c0
4d0
5e0
*/
update top (2 ) tb set tag = 1
select * from tb
/*--更新后两行
idnametag
----------- ---------- -----------
1a1
2b1
3c0
4d1
5e1
*/
;with t as
(
select top (2 ) * from tb order by id desc
)
update t set tag = 1
select * from tb
/*--删除前两行
idnametag
----------- ---------- -----------
3c0
4d1
5e1
*/
delete top (2 ) from tb
select * from tb
/*--删除后两行
idnametag
----------- ---------- -----------
3c0
*/
;with t as
(
select top (2 ) * from tb order by id desc
)
delete from t
select * from tb
set nocount off


我会在下一篇文章中介绍一个应用,就是很多人关心的如何独占查询(就是一条数据只被一个终端select到)。
如果你感兴趣的话可以自己先思考一下,我给一个提示:
SQLServer2005有一个关键字Output,它可以将更改和插入的数据输出,我们配合update top就可以模拟出来一个相对高效的独占查询的事物。此功能适合用在并行的任务处理或者消费中。

上篇:SQL分组排序去重复的小实例

下篇:MSSQL数据库占用内存过大造成服务器死机问题的解决方法