sqlserver2005 技巧
1.利用 ROW_NUMBER 实现分页
ROW_NUMBER() 就是生成一个顺序的行号,而他生成顺序的标准,就是后面紧跟的OVER(ORDER BY ReportID)。
2.TOP的参数
3.排名
4.try ... catch
5.通用表达式CTE
通过表达式可免除你过去创建临时表的麻烦。特别,通过表达式还支持递归。
6.直接发布web service
想要把store procedure变成Web Service就用这个吧,.NET, IIS都不需要,通过Windows 2003的HTTP Protocol Stack直接发布WebService,用这个功能需要Windows 2003 sp1
Web Service就发布好了,敲入http://localhost/sql/orders?wsdl得到wsdl
<注:以上内容部分来自http://walkdan.cnblogs.com/>
ROW_NUMBER() 就是生成一个顺序的行号,而他生成顺序的标准,就是后面紧跟的OVER(ORDER BY ReportID)。
--按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
select * from(
select OrderId, Freight, ROW_NUMBER() OVER(order by Freight) as row from Orders
) a
where row between 20 and 30
2.TOP的参数
--前n名的订单
declare @n int
set @n = 10
select TOP(@n) * from Orders
declare @n int
set @n = 10
select TOP(@n) * from Orders
3.排名
select * from(
select OrderId, Freight, RANK() OVER(order by Freight) as rank from Orders
) a
where rank between 20 and 30
select OrderId, Freight, RANK() OVER(order by Freight) as rank from Orders
) a
where rank between 20 and 30
4.try ... catch
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
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
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/'
)
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
<注:以上内容部分来自http://walkdan.cnblogs.com/>