sql server2005 TSql新功能学习总结(top篇)
(2008-6-11 wjf)
点击:0
回复:0
1.TOP 表达式可用在 SELECT、INSERT、UPDATE 和 DELETE 语句中。
2.Top表达式可以是常量,变量,子查询
3.取代set rowcount,可以防止锁升级,提高效率
看看下面的例题:
1
create table test2(
2
[no] int ,
3
n nvarchar(100)
4
)
5
6
insert into test2([no],n)
7
select 1,'a'
8
union
9
select 2,'b'
10
union
11
select 3,'c'
12
union
13
select 3,'c2'
14
union
15
select 2,'b2'
16
union
17
select 2,'b3'
18
go
19
20
21
select *
22
from test2
23
order by [no] asc
24
go
25
/**//*
26
no n
27
1 a
28
2 b
29
2 b2
30
2 b3
31
3 c
32
3 c2
33
*/
34
35
select top (2) *
36
from test2
37
order by [no] asc
38
go
39
/**//*
40
no n
41
1 a
42
2 b2
43
*/
44
45
-- 利用top变量
46
declare @i int
47
select @i = 2
48
select top (@i) *
49
from test2
50
order by [no] asc
51
go
52
/**//*
53
no n
54
1 a
55
2 b2
56
*/
57
58
--利用top子查询
59
select top ( select count([no]) from test2 where [no]=3 ) *
60
from test2
61
order by [no] asc
62
go
63
/**//*
64
no n
65
1 a
66
2 b2
67
*/
68
69
--指定从基本结果集中返回更多的行,返回的行与TOP n (PERCENT) 行中的最后一行在ORDER BY 列中具有相同的值。
70
--只有在指定ORDER BY 子句之后才能指定TOP
WITH TIES。
71
select top (2) WITH TIES *
72
from test2
73
order by [no] asc
74
go
75
/**//*
76
no n
77
1 a
78
2 b
79
2 b2
80
2 b3
81
*/
82
create table test2( 2
[no] int ,3
n nvarchar(100)4
)5

6
insert into test2([no],n)7
select 1,'a'8
union 9
select 2,'b'10
union 11
select 3,'c'12
union 13
select 3,'c2'14
union 15
select 2,'b2'16
union17
select 2,'b3'18
go19

20

21
select * 22
from test2 23
order by [no] asc24
go25

/**//*26
no n27
1 a28
2 b29
2 b230
2 b331
3 c32
3 c233
*/34

35
select top (2) * 36
from test2 37
order by [no] asc38
go39

/**//*40
no n41
1 a42
2 b243
*/44

45
-- 利用top变量46
declare @i int47
select @i = 248
select top (@i) * 49
from test2 50
order by [no] asc51
go52

/**//*53
no n54
1 a55
2 b256
*/57

58
--利用top子查询59
select top ( select count([no]) from test2 where [no]=3 ) * 60
from test2 61
order by [no] asc62
go63

/**//*64
no n65
1 a66
2 b267
*/68

69
--指定从基本结果集中返回更多的行,返回的行与TOP n (PERCENT) 行中的最后一行在ORDER BY 列中具有相同的值。70
--只有在指定ORDER BY 子句之后才能指定TOP
WITH TIES。71
select top (2) WITH TIES * 72
from test2 73
order by [no] asc74
go75

/**//*76
no n77
1 a78
2 b79
2 b280
2 b381
*/82


文章分类