品味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開發資料庫,