Presentation is loading. Please wait.

Presentation is loading. Please wait.

新增的 T-SQL 與資料型態 胡百敬 精誠公司恆逸資訊.

Similar presentations


Presentation on theme: "新增的 T-SQL 與資料型態 胡百敬 精誠公司恆逸資訊."— Presentation transcript:

1 新增的 T-SQL 與資料型態 胡百敬 精誠公司恆逸資訊

2 大綱 新資料類型 新的 T-SQL 語法 日期、時間 HierarchyID Geography、Geometry
複合運算子、CONVERT 函數 MERGE 陳述式 GROUPING SETS

3 新的資料類型 透過更高精準度的資料類型,建立更有彈性的時間感知(time-aware)應用程式
datetime2 date time datetimeoffset 透過大型的 UDT(User Defined Type)、UDA(User Defined Aggregate) 解決複雜的問題 最大 2 G bytes 終於!!! DateTime2 provides a much higher precision DateTime data type. This can be very important when importing data from other systems that support different date ranges. SQL Server 2008 provides separate date and time data types! This is a woo-hoo moment for SQL Server and delivers on a very common request from users. SQL Server 2008 also provides support for storing and processing time offsets with datetime data. GETDATE() has been enhanced and replaced by SYSDATETIME() and SYSDATETIMEOFFSET(). In SQL Server 2005, user-defined data types and user-defined aggregates are limited to 8K of static data. This restriction has been lifted, and these objects can now be up to 2GB in size. This allows for significantly more powerful types, such as the new system CLR types: geometry, geography, and hierarchyid.

4 日期時間資料類型 資料型態 格式 範圍 精確度 長度(byte) Datetime SmallDatetime Time Date
YYYY-MM-DD hh:mm:ss[.nnn] ~ 8 SmallDatetime YYYY-MM-DD hh:mm:ss ~ 1 分 4 Time hh:mm:ss[.nnnnnnn] 00:00: ~  23:59: 100 奈秒 3~5 Date YYYY-MM-DD ~ 1 天 3 Datetime2 YYYY-MM-DD hh:mm:ss[.nnnnnnn] :00: ~ :59: 6~8 Datetimeoffset YYYY-MM-DD hh:mm:ss[.nnnnnnn] [+|-]hh:mm :00: ~ :59: (UTC) 8 ~ 10

5 關於日期時間的新函數 回傳 DATETIME2: 回傳 DATETIMEOFFSET: SYSDATETIME
SYSDATETIMEOFFSET SYSUTCDATETIME 回傳 DATETIMEOFFSET: SWITCHOFFSET (輸入 DATETIMEOFFSET 類型) TODATETIMEOFFSET – 將輸入的日期、時間轉成指定的時區時間輸出, 而CONVERT/CAST類型轉換只是加上 UTC (+0)當時區 The SWITCHOFFSET function adjusts an input DATETIMEOFFSET value to a specified time zone, while preserving the UTC value. The syntax is SWITCHOFFSET(datetimeoffset_value, time_zone).

6 DATEPART 、DATENAME 新的部分
SELECT DATENAME(datepart,' :15: :10') microsecond nanosecond Tzoffset ISO_WEEK datepart 傳回值 year, yyyy, yy 2007 quarter, qq, q 4 month, mm, m 十月 dayofyear, dy, y 303 day, dd, d 30 week, wk, ww 44 weekday, dw 星期二 hour, hh 12 minute, n 15 second, ss, s 32 millisecond, ms 123 microsecond, mcs 123456 nanosecond, ns TZoffset, tz 310

7 HierarchyID 資料型態 呈現在階層內的位置
壓縮/有效率地儲存,實際以 VARBINARY 類型儲存 <= 900 bytes 支援任意的新增和刪除 強大的查詢方法 GetRoot、GetLevel、IsDescendantOf、 GetReparentedValue … 等等 可以透過 depth-first 或 breadth-first 索引,有效率地查詢 Modeling tree-structured data in a relational database has been done in a wide variety of inconsistent and incompatible ways. HierarchyID is the SQL Server implementation of an ORDPATH type. Applications can be built to support tree structures in a compact, efficient, and consistent way. A powerful set of query methods have been provided.

8 方法 呼叫 .NET 屬性、方法時,大小寫有別 GetLevel:傳回在樹狀結構中的深度
HIERARCHYID::GetRoot:靜態方法,傳回樹的根結點 @n 層以上的祖先 @右):傳回新的HierarchyID 之間

9 HIERARCHYID 資料類型 CREATE TABLE dbo.Employees ( empid INT NOT NULL,
hid HIERARCHYID NOT NULL, lvl AS hid.GetLevel() PERSISTED, empname VARCHAR(25) NOT NULL, salary MONEY NOT NULL ); --按照深度優先搜尋 CREATE UNIQUE CLUSTERED INDEX idx_depth_first ON dbo.Employees(hid); --按照廣度優先搜尋 CREATE UNIQUE INDEX idx_breadth_first ON dbo.Employees(lvl, hid);

10 HIERARCHYID 類型 – 增加節點 CREATE PROC dbo.usp_AddEmp
@empid AS AS INT = NULL, @empname AS AS MONEY AS AS AS HIERARCHYID, @last_child_hid AS HIERARCHYID; BEGIN TRAN IS NULL = HIERARCHYID::GetRoot(); ELSE BEGIN = (SELECT hid FROM dbo.Employees WITH (UPDLOCK) WHERE empid --傳回上一階,相同父節點的最大子結點 =(SELECT MAX(hid) FROM dbo.Employees WHERE hid.GetAncestor(1) -- 將新增的節點加在父節點的最大子節點旁 = NULL); END INSERT INTO dbo.Employees(empid, hid, empname, salary) @salary); COMMIT TRAN

11 方法 @子孫.IsDescendantOf(@祖先):如果@子孫屬於該@祖先,傳回 1
ToString():傳回呈現階層資料的格式化字串 /n/n/…

12 查詢 HIERARCHYID 類型 -- 子樹 SELECT C.* FROM dbo.Employees AS P
JOIN dbo.Employees AS C ON P.empid = 3 AND C.hid.IsDescendantOf(P.hid) = 1; -- 路徑 SELECT P.* ON C.empid = 14 -- 呈現/排序 SELECT REPLICATE(' | ', lvl) + empname AS empname, hid.ToString() AS path FROM dbo.Employees ORDER BY hid;

13 方法 HIERARCHYID::Parse:轉換 HierarchyID 標準字串表示法成 HierarchyID 的值;與 AS HIERARCHYID) 功能相同 Read( BinaryReader r):僅用在 .NET 程式撰寫,讀取從 BinaryReader 傳入的SqlHierarchyId 二進位表示法,並將 SqlHierarchyId 物件設定為該值。在 T-SQL 使用 CAST Write( BinaryWriter w):僅用在 .NET 程式撰寫, 寫出到 BinaryWriter ,在 T-SQL使用 CAST

14 方法 GetReparentedValue(@舊根, @新根):傳回將 @舊根 的部分取代為 @新根 之值 範例
當下:/1/1/2/3/2/ 舊根:/1/1/ 新根:/2/1/4/ GetReparentedValue 回傳:/2/1/4/2/3/2/

15 移動子樹 CREATE PROC dbo.usp_Reparent @empid AS INT, @new_mgrid AS INT AS
DECLARE @old_root AS AS HIERARCHYID, @new_mgr_hid AS HIERARCHYID; BEGIN TRAN = (SELECT hid FROM dbo.Employees WITH (UPDLOCK) WHERE empid = (SELECT hid FROM dbo.Employees WHERE empid -- 取得 employee 要移動的新 hid ((SELECT MAX(hid) FROM dbo.Employees WHERE hid.GetAncestor(1) NULL); -- 將所有需要移動的子孫轉換父節點 UPDATE dbo.Employees SET hid WHERE = 1; COMMIT TRAN

16 強化 T-SQL 新語法 使用者自訂資料表類型 資料表類型參數當作預存程序的參數,傳遞複雜的結構或列表
例如:建構資料表型態參數,動態地批次新增多筆記錄 透過新的 MERGE 語法整合 INSERT 、 UPDATE 和 DELETE 透過新的 Grouping Sets 簡化彙總的邏輯 A common programming requirement is to insert data if it isn’t already there but update it if it does exist. The MERGE statement provides this ability in a single automatic operation. A great side benefit is that it does so on full sets of data, not just on individual rows. This can make a huge difference in ETL processes such as in SQL Server Integration Services when maintaining data warehouses or processing data from staging tables. 資料表值參數是 SQL Server 2008 中的新參數類型。資料表值參數是使用使用者定義的資料表類型所宣告。您可以使用資料表值參數,將多個資料列傳送到 Transact-SQL 陳述式或常式 (如預存程序或函數),而不需要建立暫存資料表或許多參數。 It is also common to need to pass a list of values to a stored procedure. Most programmers accomplish this via hacks like comma-delimited lists and then have to break the list apart with table-valued UDFs. Alternatively, they have accepted the overhead of passing in XML parameters and then needing to crack those open. Table-valued parameters let you pass complex structures and lists directly into stored procedures and then have them already in a table format ready for processing in the procedure. The INSERT statement now has the ability to insert multiple rows at once. Table-valued constructors have enabled this. They can also be used in a variety of other statements, such as in the source for a MERGE statement. CUBE and ROLLUP provide limited aggregation abilities, but the new Grouping Sets provide a standard way to produce summary data. In SQL Server 2005, sp_depends suffers from a lack of full knowledge about dependencies, mostly due to deferred name resolution. SQL Server 2008 replaces sp_depends with a pair of new dynamic management functions (DMFs) that accurately reflect object dependencies, including partial dependencies when the full information is not yet known. sys.sql_expression_dependencies New catalog view; replaces sys.sql_dependencies Tracks both schema-bound and non-schema-bound dependencies Tracks cross-database and cross-server references (by name) sys.dm_sql_referenced_entities New dynamic management function; replaces sp_depends Returns a row for each entity referenced by a given entity For example, show me all objects referenced in stored procedure p1 sys.dm_sql_referencing_entities Returns a row for each entity that references a given entity For example, show me all objects that would be broken if I drop table t1

17 T-SQL 有趣的新語法 … 透過子句達成 Table Value Constructor
Assignment 運算子:+=、 -=、*=、/=、%= INSERT INTO contacts VALUES ('John Doe', ' '), ('Jane Doe', ' '), ('John Smith', ' '); SELECT * FROM   (VALUES (1, 'cust 1', '(111) ', 'address 1'),(2, 'cust 2', '(222) ', 'address 2')     ) AS C(custid, companyname, phone, address); AS MONEY = 10.00; += 2.00; UPDATE Inventory SET quantity += s.quantity FROM Inventory AS i INNER JOIN Sales AS s ON i.id = s.id

18 T-SQL 有趣的新語法 … 宣告時初始化變數 CAST/CONVERT 二進位資料型態成 16 進位字串 (例如: 0xA1BEFE)
int = 5; varchar(10) = ‘xxxxx’; AS DATETIME = CURRENT_TIMESTAMP select from t1, t2 where convert(char(4), t1.col1_of_type_binary,1) = t2.col1_of_type_char The CONVERT function is enhanced in SQL Server 2008 to support new conversion options between character strings and binary data types. You determine the conversion option to use by specifying a style number as the third argument. Style 0 is the default behavior that was supported in previous SQL Server versions—this style translates character strings to the binary representation of the ASCII codes for the characters and vice versa. Styles 1 and 2 introduce new functionality. These styles convert a hex string literal to a binary value that contains the same digits when presented in hex form and vice versa. If you use Style 1 when converting from a character string to a binary value, the input character string should include the 0x prefix; if you use Style 2, it should not. Similarly, if you use Style 1 when converting from a binary value to a character string, the output character string will contain the 0x prefix; if you use Style 2, it will not. The following example demonstrates using styles 1 and 2:

19 資料表類型參數程式碼範例 --定義自訂資料表型態 CREATE TYPE tpMyTbl AS TABLE
(ID INT, String NVARCHAR(100)) GO --定義預存程序,使用資料表型態 CREATE PROCEDURE spSelectFromTVP( @TVParam tpMyTbl READONLY) AS SET NOCOUNT ON SELECT * --宣告自訂資料表型態的變數並賦予紀錄 AS tpMyTbl INSERT String) VALUES (1, 'Fairbanks') INSERT String) VALUES (2, 'Juneau') EXEC

20 MERGE 程式碼範例 CREATE TABLE Source (id INT, name NVARCHAR(100), qty INT);
CREATE TABLE Target (id INT, name NVARCHAR(100), qty INT); -- 將 source 資料同步到 target MERGE Target AS t USING Source AS s ON t.id = s.id WHEN MATCHED AND (t.name != s.name OR t.qty!= s.qty) THEN -- 紀錄已經存在但內容不同 UPDATE SET t.name = s.name, t.qty = s.qty WHEN NOT MATCHED BY TARGET THEN -- source 存在記錄但 target 沒有 INSERT VALUES (s.id, s.name, s.qty) WHEN NOT MATCHED BY SOURCE THEN -- target 存在記錄但 source 沒有 DELETE OUTPUT $action, inserted.id, deleted.id;

21 OUTPUT 子句和 $action 函數 使用 OUTPUT 子句,回傳 MERGE 語法受影響的紀錄
使用 $action 回傳字串,代表對記錄執行何種動作 ('INSERT', 'UPDATE', 'DELERE') MERGE … OUTPUT $action, deleted.*, inserted.*;

22 MERGE 使用 Table 運算式 來源和目的地不需要是資料表,可以是資料表運算式 (view, derived table, inline table function, CTE, rowset function, OPENXML…等等) MERGE INTO dbo.Customers AS TGT USING OPENROWSET(BULK 'c:\data\custs.txt', FORMATFILE = 'c:\data\custs.fmt') AS SRC(custid, companyname, phone, address) ON … WHEN MATCHED THEN… WHEN NOT MATCHED THEN…;

23 Grouping Sets Grouping set:group by 資料行所成的集合 支援動態地分析與彙總
SQL 2008 版本之前僅有限地支援 grouping sets 相關功能 CUBE 和 ROLLUP 選項,以及 GROUPING 函數 非標準,也缺乏彈性 SQL Server 2008 大幅強化對 grouping sets 的功能

24 2008 增強的 Grouping Sets 新的符合 ISO 規範,在 Group By 子句內新增選項
CUBE ROLLUP 新的 GROUPING_ID 函數,指認 grouping set,第 n 欄若未加入群組(欄位值的內容為 NULL),傳回 2^(n-1) 的總和

25 GROUPING SETS 子句 在單一查詢內定義多個 grouping sets NULL 用作 placeholders
SELECT custid, empid, YEAR(orderdate) AS orderyear, SUM(qty) AS qty FROM dbo.Orders GROUP BY GROUPING SETS ( ( custid, empid, YEAR(orderdate) ), ( custid, YEAR(orderdate) ), ( empid, YEAR(orderdate) ), () );

26 CUBE 和 ROLLUP 子句 CUBE:輸入元素所組成的次方乘積之 grouping sets 的縮寫(n 個元素會有 2^n grouping sets) 等同 SELECT custid, empid, SUM(qty) AS qty FROM dbo.Orders GROUP BY CUBE(custid, empid); SELECT custid, empid, SUM(qty) AS qty FROM dbo.Orders GROUP BY GROUPING SETS( (custid, empid), (custid), (empid), () );

27 CUBE 和 ROLLUP 子句 ROLLUP:輸入元素所組成的階層式之grouping sets (若有 n 個元素,則有 n+1 grouping sets) 等同 SELECT ... GROUP BY ROLLUP(YEAR(orderdate), MONTH(orderdate), DAY(orderdate)); SELECT ... GROUP BY GROUPING SETS( (YEAR(orderdate), MONTH(orderdate), DAY(orderdate)), (YEAR(orderdate), MONTH(orderdate)), (YEAR(orderdate)), () );

28 Grouping Sets 代數 可以相乘 GROUPING SETS, CUBE 和 ROLLUP 子句的結果,成為交錯多種不同條件來群組
SELECT ... GROUP BY CUBE(custid, empid), ROLLUP(YEAR(orderdate), MONTH(orderdate), DAY(orderdate));

29 Grouping Sets 代數 等同 SELECT ... GROUP BY GROUPING SETS (
( custid, empid ), ( custid ), ( empid ), () ), ( YEAR(orderdate), MONTH(orderdate), DAY(orderdate) ), ( YEAR(orderdate), MONTH(orderdate) ), ( YEAR(orderdate) ), );

30 Grouping Sets 代數 等同 SELECT ... GROUP BY GROUPING SETS (
( custid, empid, YEAR(orderdate), MONTH(orderdate), DAY(orderdate) ), ( custid, empid, YEAR(orderdate), MONTH(orderdate) ), ( custid, empid, YEAR(orderdate) ), ( custid, empid ), ( custid, YEAR(orderdate), MONTH(orderdate), DAY(orderdate) ), ( custid, YEAR(orderdate), MONTH(orderdate) ), ( custid, YEAR(orderdate) ), ( custid ), ( empid, YEAR(orderdate), MONTH(orderdate), DAY(orderdate) ), ( empid, YEAR(orderdate), MONTH(orderdate) ), ( empid, YEAR(orderdate) ), ( empid ), ( YEAR(orderdate), MONTH(orderdate), DAY(orderdate) ), ( YEAR(orderdate), MONTH(orderdate) ), ( YEAR(orderdate) ), () );

31 Grouping Sets 代數 可以對全部的 grouping sets 提取共通的元素 SELECT ... GROUP BY
( ( custid, empid, YEAR(orderdate), MONTH(orderdate) ), ( custid, empid, YEAR(orderdate) ), ( custid, YEAR(orderdate), MONTH(orderdate) ), ( custid, YEAR(orderdate) ), ( empid, YEAR(orderdate), MONTH(orderdate) ), ( empid, YEAR(orderdate) ) );

32 Grouping Sets 代數 等同 SELECT ... GROUP BY YEAR(orderdate), GROUPING SETS
( custid, empid, MONTH(orderdate) ), ( custid, empid ), ( custid, MONTH(orderdate) ), ( custid ), ( empid, MONTH(orderdate) ), ( empid ) );

33 Grouping Sets 代數 等同 SELECT ... GROUP BY YEAR(orderdate), GROUPING SETS
( custid, empid ), ( custid ), ( empid ) ), ( MONTH(orderdate) ), () );

34 GROUPING_ID 接受逗號分隔的串列當作參數 產生整數 bitmap 以定義 grouping set 每個位元代表不同的元素
Bit off (0) – 元素有參與當下的 grouping set Bit on (1) –元素沒有參與當下的 grouping set

35 GROUPING_ID SELECT GROUPING_ID( custid, -- 16 empid, -- 8
YEAR(orderdate), MONTH(orderdate), DAY(orderdate) ) AS grp_id, custid, empid, YEAR(orderdate) AS orderyear, MONTH(orderdate) AS ordermonth, DAY(orderdate) AS orderday, SUM(qty) AS qty FROM dbo.Orders GROUP BY CUBE(custid, empid), ROLLUP(YEAR(orderdate), MONTH(orderdate), DAY(orderdate));

36 結論 SQL Server 2008 讓開發人員可以更有效地處理資料 空間和非結構性資料 新的資料型態 強化 T-SQL

37 相關資源 Learn more about data programmability
Learn more about spatial data Learn more about SQL Server Discover SQL Server 2008: Webcasts, Virtual Labs, and White Papers SQL Server 2008 training Download latest SQL Server CTP Join the SQL PASS community

38 1/2/ :13 AM © 2008 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION. © 2007 Microsoft Corporation. All rights reserved. Microsoft, Windows, Windows Vista and other product names are or may be registered trademarks and/or trademarks in the U.S. and/or other countries. The information herein is for informational purposes only and represents the current view of Microsoft Corporation as of the date of this presentation. Because Microsoft must respond to changing market conditions, it should not be interpreted to be a commitment on the part of Microsoft, and Microsoft cannot guarantee the accuracy of any information provided after the date of this presentation. MICROSOFT MAKES NO WARRANTIES, EXPRESS, IMPLIED OR STATUTORY, AS TO THE INFORMATION IN THIS PRESENTATION.


Download ppt "新增的 T-SQL 與資料型態 胡百敬 精誠公司恆逸資訊."

Similar presentations


Ads by Google