所有人都知道select top 的用法,但很多人還不知道update top 和 delete top 怎么用。以往的做法是set rowcount來指定,其實SQL2005中對于Top語句的增強除了參數化之外還包括對update和delete的支持,但可惜的是還不支持自定義的order by列。如果要自定義派
所有人都知道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'
/*--更新前兩行
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
如果你感興趣的話可以自己先思考一下,我給一個提示:
SQLServer2005有一個關鍵字Output,它可以將更改和插入的數據輸出,我們配合update top就可以模擬出來一個相對高效的獨占查詢的事物。此功能適合用在并行的任務處理或者消費中。
如果你想不出來,請參考后面一篇文章,如果你寫出來了,那也和我寫的比較一下吧:p
聲明:本網頁內容旨在傳播知識,若有侵權等問題請及時與本網聯系,我們將在第一時間刪除處理。TEL:177 7030 7066 E-MAIL:11247931@qq.com