品味SQL Server 2005的几个新功能
2024-08-31 00:47:48
供稿:网友
sql server 2005相对于sql server 2000改进很大,有些还是非常实用的。举几个例子来简单说明 这些例子我引用了northwind库。
1. top 表达式
sql server 2000的top是个固定值,是不是觉得不爽,现在改进了。
--前n名的订单
declare @n int
set @n = 10
select top(@n) * from orders
2. 分页
不知各位过去用sql server 2000是怎么分页的,大多都用到了临时表。sql server 2005一句话就支持分页,性能据说也非常不错。
--按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
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
sql server 2000没有异常,t-sql必须逐行检查错误代码,对于习惯了try catch程序员,2005是不是更加亲切:
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
特别,通过表达式还支持递归。
6. 直接发布web service
想要把store procedure变成web service就用这个吧,.net, iis都不需要,通过windows 2003的http protocol stack直接发布webservice,用这个功能需要windows 2003 sp1
--dataset custordersorders(string customerid)
create endpoint orders_endpoint
state=started
as http(
path='/sql/orders',
authentication=(integrated),
ports=(clear)
)
for soap(
webmethod 'custordersorders'(
name='northwind.dbo.custordersorders'
),
wsdl=default,
database='northwind',
namespace='http://mysite.org/'
)
web service就发布好了,敲入http://localhost/sql/orders?wsdl得到wsdl注册会员,创建你的web开发资料库,