SQL Server 2005改进后的几个实用新特性
SQL Server 2005相对于SQL Server 2000做了很大的改进,许些新特性是非常实用的。本文中将通过几个具体示例进行详细的说明。( 这些例子引用Northwind库) 字串5
1. TOP 表达式 字串7
SQL Server 2000的TOP是个固定值,是不是觉得差强人意,现在改进了。
--前n名的订单
declare @n int 字串5
set @n = 10 字串8
select TOP(@n) * from Orders
字串6
2. 分页 字串4
不知大家过去用SQL Server 2000是如何分页的,大多都用到了临时表。SQL Server 2005就支持分页,性能也非常不错。 字串8
--按Freight从小到大排序,求20到30行的结果 字串9
select * from(select OrderId, Freight, ROW_NUMBER() OVER(order by Freight) as row from Orders) a
where row between 20 and 30
字串9
3. 排名 字串6
select * from(select OrderId, Freight, RANK() OVER(order by Freight) as rank from Orders) a 字串7
where rank between 20 and 30
字串2
4. try ... catch 字串8
SQL Server 2000没有异常,T-SQL必须逐行检查错误代码,对于习惯了try catch程序员,2005是不是更加亲切: 字串3
SET XACT_ABORT ON -- 打开 try功能 字串9
BEGIN TRY 字串4
begin tran
insert into Orders(CustomerId) values(-1) 字串9
commit tran
字串1
print 'commited' 字串7
END TRY
字串9
BEGIN CATCH
字串3
rollback
print 'rolled back' 字串8
END CATCH
字串3
5. 通用表达式CTE 字串4
通过表达式可以免除你过去创建临时表的麻烦。 字串1
例:结合通用表达式进行分页 字串6
WITH OrderFreight AS( 字串1
select OrderId, Freight, ROW_NUMBER() OVER(order by Freight) as row from Orders
)
字串7
select OrderId, Freight from OrderFreight where row between 10 and 20
字串4
特别之处:通过表达式还可以支持递归。
字串6
文章评论
共有 0位网友发表了评论