sql2005新特性(以NorthWind数据库举例)
(1) select top 语句支持变量数目,如下例:
declare @n int
set @n=10
select top(@n) from orders
(2)分页
下例取Orders表中按freight字段排序的第20-30条记录
select * from (select orderid,freight,row_number() over(order by freight) as row from Orders) a
where row between 20 and 30
查询结果如下:
orderid freight row
----------- --------------------- -------
10873 0.82 20
10631 0.87 21
10674 0.90 22
11071 0.93 23
10620 0.94 24
10782 1.10 25
10996 1.12 26
10636 1.15 27
10295 1.15 28
10370 1.17 29
11011 1.21 30
(3),排名
select * from(select orderid,freight,rank() over(order by freight)as rank from Orders)a
where rank between 20 and 30
(4)try...catch
在些程序中的异常处理,在sql2005中也加入了
SET XACT_ABORT ON --打开try功能
BEGIN TRY
BEGIN TRAN
INSERT INTO Orders(CustomerId) VALUES(-1)
COMMIT TRAN
PRINT 'Commited'
END TRY
BEGIN CATCH
ROLLBACK
PRINT 'Rolled Back'
END CATCH
(5).通用表达式CTE(这个用着舒服)
通过表达式可免除你过去创建临时表的麻烦。
--例子:结合通用表达式进行分页
WITH OrderFreight AS(
select OrderId, Freight, ROW_NUMBER() OVER(order by Freight) as row from Orders
)
select OrderId, Freight from OrderFreight where row between 10 and 20