微软最新发布的Sql Server 2005比2000版本进步了不少。最近试用了一下,把两个版本的TSql列出来,方便大家学习。
1.外连接。
Sql Server 2000外连接既可以用outer join,也可以用*= 或 =*。2005版只能用outer join,如果执行以下语句
select * from HumanResources.Employee a, HumanResources.EmployeeAddress b
where a.EmployeeID *= b.EmployeeID
系统报错
The query uses non-ANSI outer join operators ("*=" or "=*"). To run this query without modification, please set the compatibility level for current database to 80 or lower, using stored procedure sp_dbcmptlevel. It is strongly recommended to rewrite the query using ANSI outer join operators (LEFT OUTER JOIN, RIGHT OUTER JOIN). In the future versions of SQL Server, non-ANSI join operators will not be supported even in backward-compatibility modes.
2.With
with a as
(
Select EmployeeID, ContactId from HumanResources.Employee
)
Select * from a
使用with相当于临时的视图,目的是简化代码
3.参数化Top
declare @rowcount int
select @rowcount = 5
select Top(@rowcount) * from HumanResources.Employee
4.Apply
导出表不能跟普通表Join起来,但能够使用Apply去做连接。Apply包括Cross Apply和Outer Apply。
Cross Apply:返回左表和右表都符合条件的数据集
Outer Apply:无论右表是否有符合条件的数据,左表都至少返回一条数据
以下语句是错误的:
SELECT Product.productNumber, SalesOrderAverage.averageTotal
FROM Production.Product as Product
JOIN ( SELECT AVG(lineTotal) as averageTotal
FROM Sales.SalesOrderDetail as SalesOrderDetail
WHERE product.ProductID=SalesOrderDetail.ProductID
HAVING COUNT(*) > 1
) as SalesOrderAverage
正确的语句:
SELECT Product.productNumber, SalesOrderAverage.averageTotal
FROM Production.Product as Product
CROSS APPLY ( SELECT AVG(lineTotal) as averageTotal
FROM Sales.SalesOrderDetail as SalesOrderDetail
WHERE product.ProductID=SalesOrderDetail.ProductID
HAVING COUNT(*) > 0
) as SalesOrderAverage
5.随机采样数据
SELECT * FROM sales.salesOrderDetail TABLESAMPLE SYSTEM (2 percent)
从表中随机选取2%的数据。