39
SQL Server 2008 TSQL Improvements & TSQL Improvements & Data Types Data Types Presented by Tarek Ghazali IT Technical Specialist IT Technical Specialist Microsoft SQL Server MVP, MCTS Microsoft Web Development MCP Microsoft Web Development MCP ITIL V3 Foundation Certified © 2009 Tarek Ghazali. All rights reserved.

TSQL Improvements & Data Types SQL Server 2008 TSQL Improvements & Data Types Presented by Tarek Ghazali IT Technical Specialist Microsoft SQL Server MVP,

Embed Size (px)

Citation preview

SQL Server 2008TSQL Improvements & TSQL Improvements & Data TypesData Types

Presented by Tarek GhazaliIT Technical SpecialistIT Technical SpecialistMicrosoft SQL Server MVP, MCTSMicrosoft Web Development MCPMicrosoft Web Development MCPITIL V3 Foundation Certified

© 2009 Tarek Ghazali. All rights reserved.

Overview

New Date and Time Data TypesNew Date and Time Data Types Table-Valued ParametersTable-Valued Parameters T-SQL Assign and Increment OperatorsT-SQL Assign and Increment Operators Row ConstructorsRow Constructors Grouping SetsGrouping Sets MERGE statementMERGE statement Dependency ViewsDependency Views Performance EnhancementsPerformance Enhancements

New Date and Time New Date and Time Data TypesData Types Larger Value SpaceLarger Value Space

– Current DATETIME - 1753-9999 Current DATETIME - 1753-9999 YearsYears

– Current DATETIME - 0.00333 Second Current DATETIME - 0.00333 Second AccuracyAccuracy

– New Date Types - 0001-9999 YearsNew Date Types - 0001-9999 Years– New Date/Time Types - Precisions to New Date/Time Types - Precisions to

100 nanoseconds100 nanoseconds

New Date and Time New Date and Time Data Types (Cont.)Data Types (Cont.)

SQL Server 2008 extends SQL Server 2008 extends date/time supportdate/time support

Variable Precision Saves SpaceVariable Precision Saves Space Separate Date and Time Saves Separate Date and Time Saves

Space Space ANSI CompatibleANSI Compatible

Date/Time Types Date/Time Types CompatibilityCompatibility New Data Types Use Same T-SQL New Data Types Use Same T-SQL

FunctionsFunctions– DATENAME (datepart, date)DATENAME (datepart, date)– DATEPART (datepart,date)DATEPART (datepart,date)– DATEDIFF (datepart, startdate, DATEDIFF (datepart, startdate,

enddate)enddate)– DATEADD (datepart, number, date)DATEADD (datepart, number, date)

Datepart can also be microsecond, Datepart can also be microsecond, nanosecond, TZoffsetnanosecond, TZoffset

Date/Time Types Date/Time Types Compatibility (Cont.)Compatibility (Cont.)

– MONTHMONTH– DAYDAY– YEARYEAR– CONVERT extensionsCONVERT extensions

Date Time Library Date Time Library ExtensionsExtensions Higher precision date/time usesHigher precision date/time uses

– SYSDATETIMESYSDATETIME– SYSUTCDATETIMESYSUTCDATETIME– SYSDATETIMEOFFSETSYSDATETIMEOFFSET

Original date/time usesOriginal date/time uses– GETDATE, GETUTCDATE, GETDATE, GETUTCDATE,

CURRENT_TIMESTAMPCURRENT_TIMESTAMP– ISDATE(datetime/smalldatetime)ISDATE(datetime/smalldatetime)

Date Time Library Date Time Library Extensions (Cont.)Extensions (Cont.)

Special functions for Special functions for DATETIMEOFFSETDATETIMEOFFSET– SWITCHOFFSET(datetimeoffset, SWITCHOFFSET(datetimeoffset,

timezone)timezone)– TODATETIMEOFFSET(datetime, TODATETIMEOFFSET(datetime,

timezone)timezone)

Localization FunctionsLocalization Functions

All Date/Time Types Support All Date/Time Types Support LocalizationLocalization– SET DATEFIRSTSET DATEFIRST– SET DATEFORMATSET DATEFORMAT– SET LANGUAGE - affects some SET LANGUAGE - affects some

date/time functionsdate/time functions– @@DATEFIRST@@DATEFIRST– @@LANGUAGE@@LANGUAGE

Date/Time and StringsDate/Time and Strings

Dates are input and output in string Dates are input and output in string formatformat

String (varchar) can be output through String (varchar) can be output through CAST/CONVERTCAST/CONVERT

CONVERT has extensions for date/time CONVERT has extensions for date/time typestypes

Dates are input in a variety of formatsDates are input in a variety of formats– Some of language-sensitive, some notSome of language-sensitive, some not

Table-Valued Table-Valued ParametersParameters

Inserts into structures with 1-n Inserts into structures with 1-n cardinality problematiccardinality problematic– One order -> N order line itemsOne order -> N order line items– "N" is variable and can be large"N" is variable and can be large– Don't want to force a new order for Don't want to force a new order for

every 20 line itemsevery 20 line items

Table-Valued Table-Valued Parameters (Cont.)Parameters (Cont.) One database round-trip / line One database round-trip / line

item slows things downitem slows things down– No ARRAY data type in SQL ServerNo ARRAY data type in SQL Server– XML composition/decomposition XML composition/decomposition

used as an alternativeused as an alternative Table-valued parameters solve Table-valued parameters solve

this problemthis problem

Common challenge: Common challenge: Passing list of values to Passing list of values to SP/FNSP/FNProblemProblem: No ARRAY data type : No ARRAY data type

SQL Server 2005

@p = '1,2,3,4,5,…'

Parsing string of delimited values

Shredding XML

SQL Server 2008

temp table outside the SP

Table Value Parameter

Table TypesTable Types

SQL Server has table variablesSQL Server has table variables– DECLARE @t TABLE (id int);DECLARE @t TABLE (id int);

SQL Server 2008 adds strongly SQL Server 2008 adds strongly typed table variablestyped table variables– CREATE TYPE mytab AS TABLE (id int);CREATE TYPE mytab AS TABLE (id int);– DECLARE @t mytab;DECLARE @t mytab;

Parameters must use strongly Parameters must use strongly typed table variables typed table variables

Table Variables are Table Variables are Input OnlyInput Only

Declare and initialize TABLE Declare and initialize TABLE variablevariable– DECLARE @t mytab;DECLARE @t mytab;– INSERT @t VALUES (1), (2), (3);INSERT @t VALUES (1), (2), (3);– EXEC myproc @t;EXEC myproc @t;

Table Variables are Table Variables are Input Only (Cont.)Input Only (Cont.) Procedure must declare variable Procedure must declare variable

READONLYREADONLY– CREATE PROCEDURE usetable (CREATE PROCEDURE usetable (– @t mytab READONLY ...)@t mytab READONLY ...)– ASAS– INSERT INTO lineitems SELECT * INSERT INTO lineitems SELECT *

FROM @t;FROM @t;– UPDATE @t SET... -- no!UPDATE @t SET... -- no!

T-SQL Syntax T-SQL Syntax EnhancementsEnhancements Single statement declare and initializeSingle statement declare and initialize

– DECLARE @i int = 4;DECLARE @i int = 4; Increment Operators: SET @i += 1;Increment Operators: SET @i += 1; Row constructorsRow constructors

– DECLARE @t TABLE (id int, name DECLARE @t TABLE (id int, name varchar(20));varchar(20));

– INSERT INTO @t VALUESINSERT INTO @t VALUES– (1, 'Fred'), (2, 'Jim'), (3, 'Sue');(1, 'Fred'), (2, 'Jim'), (3, 'Sue');

Grouping SetsGrouping Sets

Grouping Sets allow multiple GROUP Grouping Sets allow multiple GROUP BY clauses in a single SQL statementBY clauses in a single SQL statement– Multiple, arbitrary, sets of subtotalsMultiple, arbitrary, sets of subtotals– Single read pass for performanceSingle read pass for performance– Nested subtotals provide ever better Nested subtotals provide ever better

performanceperformance Grouping Sets are an ANSI-standardGrouping Sets are an ANSI-standard

– COMPUTE BY is deprecatedCOMPUTE BY is deprecated

Common challengeCommon challenge: Many grouping sub-totals required : Many grouping sub-totals required from the same tablefrom the same table

SQL Server 2005 SQL Server 2008

SELECT a, sum(q)SELECT a, sum(q)FROM TFROM TGROUP BY aGROUP BY a

UNION ALLUNION ALLSELECT a, b, sum(q)SELECT a, b, sum(q)FROM TFROM TGROUP BY a, bGROUP BY a, b

UNION ALLUNION ALLSELECT a, b, c, sum(q)SELECT a, b, c, sum(q)FROM TFROM TGROUP BY a, b, cGROUP BY a, b, c

SELECT a, sum(q)SELECT a, sum(q)FROM TFROM TGROUP BY aGROUP BY a

UNION ALLUNION ALLSELECT a, b, sum(q)SELECT a, b, sum(q)FROM TFROM TGROUP BY a, bGROUP BY a, b

UNION ALLUNION ALLSELECT a, b, c, sum(q)SELECT a, b, c, sum(q)FROM TFROM TGROUP BY a, b, cGROUP BY a, b, c

SELECT a, b, c, sum(q) FROM TGROUP BY

GROUPING SETS ( (a), (b), (a, b, c))

SELECT a, b, c, sum(q) FROM TGROUP BY

GROUPING SETS ( (a), (b), (a, b, c))

GROUPING SETS, GROUPING SETS, ROLLUP, and CUBEROLLUP, and CUBE SQL Server 2008 - ANSI-syntax SQL Server 2008 - ANSI-syntax

ROLLUP and CUBEROLLUP and CUBE– Pre-2008 non-ANSI syntax is Pre-2008 non-ANSI syntax is

deprecateddeprecated WITH ROLLUP produces n+1 WITH ROLLUP produces n+1

different groupings of datadifferent groupings of data– where n is the number of columns in where n is the number of columns in

GROUP BYGROUP BY

GROUPING SETS, GROUPING SETS, ROLLUP, & CUBE ROLLUP, & CUBE (Cont.)(Cont.) WITH CUBE produces 2^n different WITH CUBE produces 2^n different

groupingsgroupings– where n is the number of columns in where n is the number of columns in

GROUP BYGROUP BY GROUPING SETS provide a "halfway GROUPING SETS provide a "halfway

measure"measure"– More groupings than ROLLUP, but less More groupings than ROLLUP, but less

than CUBEthan CUBE Grouping Sets are visible in query planGrouping Sets are visible in query plan

GROUPING_ID and GROUPING_ID and GROUPINGGROUPING Grouping Sets can produce non-Grouping Sets can produce non-

homogeneous setshomogeneous sets– Grouping set includes NULL values Grouping set includes NULL values

for group membersfor group members– Need to distinguish by grouping and Need to distinguish by grouping and

NULL valuesNULL values

GROUPING_ID and GROUPING_ID and GROUPING (Cont.)GROUPING (Cont.) GROUPING (column expression) GROUPING (column expression)

returns 0 or 1returns 0 or 1– Is this a group based on column Is this a group based on column

expr. or NULL value?expr. or NULL value? GROUPING_ID (a,b,c) is a bitmaskGROUPING_ID (a,b,c) is a bitmask

– GROUPING_ID bits are set based on GROUPING_ID bits are set based on column expressions a, b, and ccolumn expressions a, b, and c

MERGE StatementMERGE Statement

Multiple set operations in a single Multiple set operations in a single SQL statementSQL statement

Uses multiple sets as inputUses multiple sets as input– MERGE target USING source ON ...MERGE target USING source ON ...

Operations can be INSERT, Operations can be INSERT, UPDATE, DELETEUPDATE, DELETE

MERGE Statement MERGE Statement (Cont.)(Cont.) Operations based onOperations based on

– WHEN MATCHEDWHEN MATCHED– WHEN [TARGET] NOT MATCHEDWHEN [TARGET] NOT MATCHED– WHEN SOURCE NOT MATCHEDWHEN SOURCE NOT MATCHED

ANSI SQL 2006 compliant - with ANSI SQL 2006 compliant - with extensionsextensions

What is to merge What is to merge data?data?

Merged DataSource

Update

Insert

Delete

MERGE StatementMERGE Statement

SQL Server 2005: SQL Server 2005: Multiple DML Statements:Multiple DML Statements:

SQL Server 2008: A Single DML Statement

BEGIN TRAN

COMMIT

UPDATE tbl INNER JOIN s

INSERT tbl LEFT OUTER JOIN

DELETE tbl RIGHT JOIN s

MERGE tblUSING s ON tbl.ID = s.ID

WHEN MATCHED THEN UPDATE

WHEN NOT MATCHEDTHEN INSERT

WHEN NOT MATCHED BY SOURCE THEN DELETE;

More on MERGEMore on MERGE

MERGE statement can reference a MERGE statement can reference a $action column$action column– Used when MERGE used with OUTPUT Used when MERGE used with OUTPUT

clauseclause Multiple WHEN clauses possible Multiple WHEN clauses possible

– For MATCHED and SOURCE NOT For MATCHED and SOURCE NOT MATCHEDMATCHED

– Only one WHEN clause for TARGET NOT Only one WHEN clause for TARGET NOT MATCHEDMATCHED

More on MERGE (Cont.)More on MERGE (Cont.)

MERGE can be used with any MERGE can be used with any table sourcetable source

A MERGE statement causes A MERGE statement causes triggers to be fired oncetriggers to be fired once

Rows affected includes total rows Rows affected includes total rows affected by all clausesaffected by all clauses

MERGE PerformanceMERGE Performance

MERGE statement is transactionalMERGE statement is transactional– No explicit transaction requiredNo explicit transaction required

One Pass Through TablesOne Pass Through Tables– At most a full outer joinAt most a full outer join– Matching rows = when matchedMatching rows = when matched– Left-outer join rows = when target not Left-outer join rows = when target not

matchedmatched– Right-outer join rows = when source not Right-outer join rows = when source not

matchedmatched

MERGE and MERGE and DeterminismDeterminism UPDATE using a JOIN is non-UPDATE using a JOIN is non-

deterministicdeterministic– If more than one row in source matches If more than one row in source matches

ON clause, either/any row can be used ON clause, either/any row can be used for the UPDATEfor the UPDATE

MERGE is deterministicMERGE is deterministic– If more than one row in source matches If more than one row in source matches

ON clause, ON clause, – its an errorits an error

Keeping Track of Keeping Track of DependenciesDependencies New dependency views replace New dependency views replace

sp_dependssp_depends Dependency views are kept in sync Dependency views are kept in sync

as changes occuras changes occur sys.dm_sql_referenced_entities sys.dm_sql_referenced_entities

– Lists all named entities that an object Lists all named entities that an object referencesreferences

– Example: which objects does this stored Example: which objects does this stored procedure use?procedure use?

Keeping Track of Keeping Track of Dependencies (Cont.)Dependencies (Cont.) sys.dm_sql_referencing_entitiessys.dm_sql_referencing_entities

– Lists all named entities that use an Lists all named entities that use an objectobject

– Example: which objects use this Example: which objects use this table?table?

Can see references at OBJECT, Can see references at OBJECT, DATABASE DDL TRIGGER, DATABASE DDL TRIGGER, SERVER DDL TRIGGER levelSERVER DDL TRIGGER level

Performance Performance EnhancementsEnhancements MERGE and GROUPING SETS offer MERGE and GROUPING SETS offer

improvementsimprovements– Less scans through tableLess scans through table

Table-valued parameters offer Table-valued parameters offer improvementsimprovements– Less round trips to databaseLess round trips to database

Performance Performance Enhancements (Cont.)Enhancements (Cont.) Improvements for data Improvements for data

warehouse querieswarehouse queries– Earlier predicate filteringEarlier predicate filtering– Multiple bitmap iterators per queryMultiple bitmap iterators per query

Plan Guide ImprovementsPlan Guide Improvements– Easier to create plan guidesEasier to create plan guides– Plan guides on DML statementsPlan guides on DML statements

ReviewReview

New SQL types increase the utility, New SQL types increase the utility, improve storage requirements of improve storage requirements of date time type seriesdate time type series

Strongly typed table-valued Strongly typed table-valued parameters help the database parameters help the database round trip problemround trip problem

Grouping Sets allow arbitrary group Grouping Sets allow arbitrary group by clauses for subtotals and totalsby clauses for subtotals and totals

Review (Cont)Review (Cont)

MERGE statement allows set-to-MERGE statement allows set-to-set comparison and multiple set comparison and multiple deterministic operationsdeterministic operations– ANSI standard compliance with ANSI standard compliance with

extensionsextensions Object reference tracking makes Object reference tracking makes

schema and procedural code schema and procedural code versioning less error-proneversioning less error-prone

DemoDemo

Resources & QuestionsResources & Questions

Microsoft Resources:Microsoft Resources:– http://msdn.microsoft.com/sqlserver/http://msdn.microsoft.com/sqlserver/– http://www.microsoft.com/sql/communityhttp://www.microsoft.com/sql/community

Contact me: Contact me: – [email protected]@sqlmvp.com

Download Presentation:Download Presentation:– http://www.sqlmvp.comhttp://www.sqlmvp.com