解析SQLServer2005的Top功能
發(fā)布日期:2022-01-02 01:40 | 文章來(lái)源:源碼中國(guó)
我們看下面的測(cè)試代碼。
復(fù)制代碼 代碼如下:
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'
/*--更新前兩行
id name tag
----------- ---------- -----------
1 a 1
2 b 1
3 c 0
4 d 0
5 e 0
*/
update top (2 ) tb set tag = 1
select * from tb
/*--更新后兩行
id name tag
----------- ---------- -----------
1 a 1
2 b 1
3 c 0
4 d 1
5 e 1
*/
;with t as
(
select top (2 ) * from tb order by id desc
)
update t set tag = 1
select * from tb
/*--刪除前兩行
id name tag
----------- ---------- -----------
3 c 0
4 d 1
5 e 1
*/
delete top (2 ) from tb
select * from tb
/*--刪除后兩行
id name tag
----------- ---------- -----------
3 c 0
*/
;with t as
(
select top (2 ) * from tb order by id desc
)
delete from t
select * from tb
set nocount off
我會(huì)在下一篇文章中介紹一個(gè)應(yīng)用,就是很多人關(guān)心的如何獨(dú)占查詢(就是一條數(shù)據(jù)只被一個(gè)終端select到)。
如果你感興趣的話可以自己先思考一下,我給一個(gè)提示:
SQLServer2005有一個(gè)關(guān)鍵字Output,它可以將更改和插入的數(shù)據(jù)輸出,我們配合update top就可以模擬出來(lái)一個(gè)相對(duì)高效的獨(dú)占查詢的事物。此功能適合用在并行的任務(wù)處理或者消費(fèi)中。
版權(quán)聲明:本站文章來(lái)源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請(qǐng)保持原文完整并注明來(lái)源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來(lái)源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來(lái),僅供學(xué)習(xí)參考,不代表本站立場(chǎng),如有內(nèi)容涉嫌侵權(quán),請(qǐng)聯(lián)系alex-e#qq.com處理。
相關(guān)文章