T-SQL语法增强
简化T-SQL语句的编写:可宣布变量并同时初始化,例如:DECLARE @i INT=4。以及附和运算,例如:+= 、 -= 、 *= 、/= 、%= 等。
Values子句提供资料列构建函式:可用在单一INSERT陈述式内,同时插入多组值,例如
INSERT INTO tb VALUES (1, 'Fred'), (2, 'Jim'), (3, 'Sue');
或用在 SELECT 語法:
或用在SELECT语句:
SELECT * FROM (VALUES (1, 'Fred'), (2, 'Jim'), (3, 'Sue')) tb(C1,C2)
或用在 SELECT 語法:
或用在SELECT语句:
SELECT * FROM (VALUES (1, 'Fred'), (2, 'Jim'), (3, 'Sue')) tb(C1,C2)
Merge语句:遵循ANSI SQL 2006 的 Merge定义并加以延伸。比较来源与目的资料后,以一句Merge语句同时完成新增、修改、删除等操作。如同单一句SQL语句自动含在交互内,通过Merge语句所有更新的资料都包在一个交互内,不像以往需明确定义交互,然后包含多句变更资料的DML语句。
Group By 子句支持 ANSI 标准的 Grouping Sets:简化组合各种群组的语句,并可搭配 Rollup、Cube。例如,以往若要分別呈现群组不同字段,需要写如下的查询:
use Northwind
GO
SELECT OrderID,NULL AS ProductID,SUM(Quantity) AS TOTAL FROM [Order Details]
GROUP BY OrderID
UNION ALL
SELECT NULL AS OrderID,ProductID,SUM(Quantity) AS TOTAL FROM [Order Details]
GROUP BY ProductID
GO
SELECT OrderID,NULL AS ProductID,SUM(Quantity) AS TOTAL FROM [Order Details]
GROUP BY OrderID
UNION ALL
SELECT NULL AS OrderID,ProductID,SUM(Quantity) AS TOTAL FROM [Order Details]
GROUP BY ProductID
在SQL Server 2008后,可改成如下的写法:
SELECT OrderID,ProductID,SUM(Quantity) AS TOTAL
FROM dbo.[Order Details]
GROUP BY GROUPING SETS ((OrderID), (ProductID))
FROM dbo.[Order Details]
GROUP BY GROUPING SETS ((OrderID), (ProductID))