微軟最新發布的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%的數據。