Presentation is loading. Please wait.

Presentation is loading. Please wait.

SQL Server 2008 T-SQL Enhancements SELECT TOP(10) t_sql_enhancements

Similar presentations


Presentation on theme: "SQL Server 2008 T-SQL Enhancements SELECT TOP(10) t_sql_enhancements"— Presentation transcript:

1 SQL Server 2008 T-SQL Enhancements SELECT TOP(10) t_sql_enhancements
FROM SQLServer2008 ORDER BY CHECKSUM(NEWID()); Plamen Ratchev Tangra, Inc.

2 Quiz How many new T-SQL features do you see?
INT = (SELECT MAX(customer_nbr) FROM Customers); += 1; INSERT INTO Customers VALUES 'John Doe'), + 1, 'Jane Fisher'); VALUES ((SELECT MAX(customer_nbr) + 1 FROM Customers), 'Jeff Brown');

3 Quiz Would this SQL statement run?
INSERT INTO LoansHistory (loan_nbr, loan_amount, loan_date) SELECT loan_nbr, loan_amount, loan_date FROM (DELETE Loans OUTPUT deleted.loan_nbr, deleted.loan_amount, deleted.loan_date WHERE loan_date < ' ') AS L;

4 Agenda Delighters Row constructors MERGE Composable DML
Table valued parameters Filtered indexes Sparse columns Hierarchy ID Date and Time data types FILESTREAM data type

5 Delighters Inline variable initialization and compound assignment
INT = 1; += 1; /= 2; *= 5; %= 3; -= 1; UPDATE PayRates SET pay_rate *= performance_score * 0.25; DECIMAL(15, 2) = (SELECT MAX(pay_rate) FROM PayRates);

6 Row constructors -- Insert data using row constructors
INSERT INTO Employees (employee_nbr, employee_name) VALUES (1, 'Jim Smith'), (2, 'Joe Doe'), (3, 'Greg Brown'), (4, 'Donna Ford'); -- Inline table expression SELECT employee_nbr, employee_name FROM (VALUES (1, 'Jim Smith'), (4, 'Donna Ford') ) AS E(employee_nbr, employee_name);

7 MERGE Statement Definition
The MERGE syntax consists of four primary clauses: The MERGE clause specifies the table or view that is the target of the INSERT, UPDATE, or DELETE operations. The USING clause specifies the data source being joined with the target. The ON clause specifies the join conditions to determine where the target and source match. The WHEN clauses specify the actions to take based on the results of the ON clause.

8 MERGE Statement Syntax
[ WITH <common_table_expression> [,...n] ] MERGE [ TOP ( expression ) [ PERCENT ] ] [ INTO ] target_table [ [ AS ] table_alias ] [ WITH ( <merge_hint> ) ] USING <table_source> ON <search_condition> [ WHEN MATCHED [ AND <search_condition> ] THEN <merge_matched> ] [ WHEN [TARGET] NOT MATCHED [ AND <search_condition> ] THEN <merge_not_matched> ] [ WHEN SOURCE NOT MATCHED [ AND <search_condition> ] THEN <merge_ matched> ] <output_clause> [ OPTION ( <query_hint> [ ,...n ] ) ] ;

9 MERGE Statement Example: Update existing and add missing
MERGE INTO CentralOfficeAccounts AS C -- Target USING BranchOfficeAccounts AS B -- Source ON C.account_nbr = B.account_nbr WHEN MATCHED THEN On match update UPDATE SET C.company_name = B.company_name, C.primary_contact = B.primary_contact, C.contact_phone = B.contact_phone WHEN NOT MATCHED THEN -- Add missing INSERT (account_nbr, company_name, primary_contact, contact_phone) VALUES (B.account_nbr, B.company_name, B.primary_contact, B.contact_phone);

10 MERGE Statement Example: Update existing that changed and add missing
MERGE INTO CentralOfficeAccounts AS C -- Target USING BranchOfficeAccounts AS B -- Source ON C.account_nbr = B.account_nbr WHEN MATCHED On match update AND (C.company_name <> B.company_name -- Additional search conditions OR C.primary_contact <> B.primary_contact OR C.contact_phone = B.contact_phone) THEN UPDATE SET C.company_name = B.company_name, C.primary_contact = B.primary_contact, C.contact_phone = B.contact_phone WHEN NOT MATCHED THEN -- Add missing INSERT (account_nbr, company_name, primary_contact, contact_phone) VALUES (B.account_nbr, B.company_name, B.primary_contact, B.contact_phone);

11 MERGE Statement Example: Update existing that changed and add missing, delete missing in source
MERGE INTO CentralOfficeAccounts AS C -- Target USING BranchOfficeAccounts AS B -- Source ON C.account_nbr = B.account_nbr WHEN MATCHED On match update AND (C.company_name <> B.company_name OR C.primary_contact <> B.primary_contact OR C.contact_phone = B.contact_phone) THEN UPDATE SET C.company_name = B.company_name, C.primary_contact = B.primary_contact, C.contact_phone = B.contact_phone WHEN NOT MATCHED THEN -- Add missing INSERT (account_nbr, company_name, primary_contact, contact_phone) VALUES (B.account_nbr, B.company_name, B.primary_contact, B.contact_phone) WHEN SOURCE NOT MATCHED THEN -- Delete missing from source DELETE;

12 Composable DML INSERT INTO AccountsAudit
(account_nbr, change_action, old_company_name, new_company_name) SELECT account_nbr, merge_action, old_company_name, new_company_name FROM (MERGE INTO CentralOfficeAccounts AS C USING BranchOfficeAccounts AS B ON C.account_nbr = B.account_nbr WHEN MATCHED AND C.company_name <> B.company_name THEN UPDATE SET C.company_name = B.company_name WHEN NOT MATCHED THEN INSERT (account_nbr, company_name, primary_contact, contact_phone) VALUES (B.account_nbr, B.company_name, B.primary_contact, B.contact_phone) WHEN SOURCE NOT MATCHED THEN DELETE OUTPUT $action, COALESCE(inserted.account_nbr, deleted.account_nbr), deleted.company_name, inserted.company_name ) AS T(merge_action, account_nbr, old_company_name, new_company_name);

13 Table valued parameters
-- User-defined table type CREATE TYPE LoanTable AS TABLE ( loan_nbr INT PRIMARY KEY, loan_date DATETIME, loan_amount DECIMAL(15, 2)); -- Procedure with table valued parameter -- Must use the READONLY clause CREATE PROCEDURE InsertLoans @Loans LoanTable READONLY AS INSERT INTO Loans SELECT loan_nbr, loan_date, loan_amount -- Declare table variable of the new type LoanTable; -- Insert new loans using the table variable as parameter EXEC

14 Table valued parameters Client side ADO. NET (v3
Table valued parameters Client side ADO.NET (v3.5) support for table valued parameters DataTable loans; loans = new DataTable(); loans.Columns.Add("loan_nbr", typeof(int)); loans.Columns.Add("loan_date", typeof(System.DateTime)); loans.Columns.Add("loan_amount", typeof(decimal)); using(SqlCommand cmd = new SqlCommand("InsertLoans", conn) { cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("Loans", loans); cmd.ExecuteNonQuery(); }

15 Filtered indexes CREATE NONCLUSTERED INDEX ix_SouthEastRegion
ON Regions (region_cd) INCLUDE(region_name, region_phone) WHERE region_cd = 'SE'; SELECT region_cd, region_name, region_phone FROM Regions WHERE region_cd = 'SE'; SELECT region_cd, region_name, region_phone FROM Regions WHERE region_cd = ‘NE';

16 Filtered indexes -- Guarantee unique values excuding NULLs
CREATE UNIQUE NONCLUSTERED INDEX ix_RegionPhone ON Regions (region_phone) WHERE region_phone IS NOT NULL; -- OK INSERT INTO Regions VALUES ('NW', 'North West', NULL); -- Error: -- Cannot insert duplicate key row in object 'dbo.Regions' -- with unique index 'ix_RegionPhone‘. INSERT INTO Regions VALUES ('NW', 'North West', ' ');

17 Sparse columns Pros: Storing NULL in a sparse column takes up no space at all Up to 30,000 columns To any external application the column will behave the same Sparse columns fit well with filtered indexes to index on non-empty values Cons: If a sparse column has data it takes 4 more bytes than a normal column Not all data types can be sparse: TEXT, NTEXT, IMAGE, TIMESTAMP, user-defined data types, GEOMETRY, GEOGRAPHY, and VARBINARY(MAX) with the FILESTREAM attribute Computed columns cannot be sparse Cannot have default values

18 Sparse columns CREATE TABLE Survey (
survey_nbr INT NOT NULL PRIMARY KEY, survey_desc VARCHAR(30), survey_info1 VARCHAR(30) SPARSE NULL, survey_info2 VARCHAR(30) SPARSE NULL, survey_info3 VARCHAR(30) SPARSE NULL, survey_info4 VARCHAR(30) SPARSE NULL); INSERT INTO Survey(survey_nbr, survey_desc, survey_info1) VALUES(1, 'Survey 1', 'some data'), (2, 'Survey 2', 'good');

19 Sparse columns Column sets
CREATE TABLE Survey ( survey_nbr INT NOT NULL PRIMARY KEY, survey_desc VARCHAR(30), survey_info1 VARCHAR(30) SPARSE NULL, survey_info2 VARCHAR(30) SPARSE NULL, survey_info3 VARCHAR(30) SPARSE NULL, survey_info4 VARCHAR(30) SPARSE NULL, survey_set XML column_set FOR ALL_SPARSE_COLUMNS); INSERT INTO Survey(survey_nbr, survey_desc, survey_set) VALUES(3, 'Survey 3', '<survey_info3>data 3</survey_info3> <survey_info4>answer 4</survey_info4>'); Defined as XML data type column Not stored, like computed column, but updatable Only one column set per table Cannot be changed Cannot be added if the table already has sparse columns Limited by XML data size limit of 2 GB (all sparse columns in a row cannot exceed 2 GB) Cannot define constraints or default values Allows to update or insert sparse column values On update all sparse columns are updated, when no value provided sets the column to NULL

20 Graphs and Trees with HIERARCHYID
Compact storage Convenient methods for nodes manipulation Single root Does not automatically represent a tree; application has to define relationships Application needs to manage consistency

21 Graphs and Trees with HIERARCHYID
CREATE TABLE Employees ( emp_id INT NOT NULL PRIMARY KEY, emp_name VARCHAR(35), manager_id INT REFERENCES Employees(emp_id), org_chart_path HIERARCHYID); -- Insert the top level manager as hierarchy root INSERT INTO Employees VALUES (1, 'Jeff Brown', NULL, hierarchyid::GetRoot()); -- Insert John who reports to the top level manager VALUES (2, 'John Doe', 1, (SELECT hierarchyid::GetRoot().GetDescendant(NULL, NULL) FROM Employees));

22 Graphs and Trees with HIERARCHYID
-- Insert Peter at the same level as John HIERARCHYID = (SELECT org_chart_path FROM Employees WHERE emp_name = 'John Doe'); INSERT INTO Employees VALUES (3, 'Peter Hanna', 1, (SELECT NULL) WHERE org_chart_path = hierarchyid::GetRoot())); -- Insert Richard as reporting to John VALUES (4, 'Richard Burns', 2, hierarchyid::Parse('/1/1/')); -- Also: CAST('/1/1/' AS HIERARCHYID) SELECT emp_id, emp_name, manager_id, org_chart_path, org_chart_path.GetAncestor(1) AS emp_manager, hierarchyid::GetRoot() AS top_manager, org_chart_path.GetDescendant(NULL, NULL) AS emp_descendant, org_chart_path.GetLevel() AS emp_level, org_chart_path.ToString() AS emp_org_path FROM Employees;

23 Graphs and Trees with HIERARCHYID
-- Move Richard to report to Peter HIERARCHYID = (SELECT org_chart_path FROM Employees WHERE emp_name = 'Peter Hanna'); UPDATE Employees SET org_chart_path = org_chart_path.Reparent(org_chart_path.GetAncestor(1), @new_mgr) WHERE emp_name = 'Richard Burns';

24 Date and Time data types
DATE ( through ) TIME (00:00: through 23:59: ) DATETIME2 (fraction 0 through 7) DATETIMEOFFSET (time zone awareness) Functions: SYSDATETIME SYSDATETIMEOFFSET SYSUTCDATETIME SWITCHOFFSET TODATETIMEOFFSET

25 FILESTREAM data type Implemented as VARBINARY(MAX)
No limitation of 2 GB Stored in the file system Fast read access Good for objects larger then ~ MB Encryption is not supported Setting to NULL deletes the BLOB data Transactional consistency Windows access via the OpenSqlFilestream APIs (read/write; no delete or rename) Uses Windows cache not using SQL Server buffer pool, more memory for queries A ROWGUIDCOL column is required to use FILESTREAM data with Win32 APIs

26 FILESTREAM data type Enabling FILESTREAM EXEC sp_filestream_configure
Levels: 0 - Disabled. This is the default value 1 - Enabled only for Transact-SQL access 2 - Enabled only for Transact-SQL and local file system access. 3 - Enabled for Transact-SQL, local file system access, and remote file system access. Create database supporting FILESTREAM and table with FILESTREAM column EXEC sp_filestream_configure @enable_level = 3, @share_name = "FileStreamShare"; CREATE DATABASE BlobDatabase ON PRIMARY ( NAME = Blob, FILENAME = 'C:\Data\Blob.mdf'), FILEGROUP FSGroup CONTAINS FILESTREAM ( NAME = BlobFS, FILENAME = 'C:\Data\FileStream') LOG ON ( NAME = BlobLog, FILENAME = 'C:\Data\Blob.ldf'); CREATE TABLE BlobDatabase.dbo.Images ( image_id UNIQUEIDENTIFIER ROWGUIDCOL NOT NULL UNIQUE, image_desc VARCHAR(35), image_data VARBINARY(MAX) FILESTREAM NULL);

27 What else? New data types Spatial data (GEOMETRY and GEOGRAPHY)
Grouping Sets Function changes Table hints (FORCESEEK) Star join query optimizations T-SQL debugger is back


Download ppt "SQL Server 2008 T-SQL Enhancements SELECT TOP(10) t_sql_enhancements"

Similar presentations


Ads by Google