50

DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

Embed Size (px)

Citation preview

Page 1: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation
Page 2: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead?

DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead?

Gert E.R. DrapersGert E.R. DrapersSoftware ArchitectSoftware ArchitectMicrosoft CorporationMicrosoft Corporation

Page 3: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

OverviewOverview

Ranking functions Ranking functions

Relation OperatorsRelation Operators

TOP (%n) TOP (%n)

Recursive queries Recursive queries

Index & Indexed Views improvementsIndex & Indexed Views improvements

XML showplanXML showplan

Snapshot isolation levelSnapshot isolation level

Data typesData types

DRI changesDRI changes

DDL triggersDDL triggers

DML with outputDML with output

Exception HandlingException Handling

Page 4: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

Ranking FunctionsRanking Functions

Ranking functions in Yukon Ranking functions in Yukon RANK()RANK()

DENSE_RANK()DENSE_RANK()

NTILE(<expression>) NTILE(<expression>)

ROW_NUMBER() ROW_NUMBER()

Syntax based on SQL-99 OLAP ExtensionsSyntax based on SQL-99 OLAP Extensions<ranking_function><ranking_function>OVER([<partition_clause>] <order_by_clause>)OVER([<partition_clause>] <order_by_clause>)

Page 5: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

Ranking Functions ScenariosRanking Functions Scenarios

Data analysisData analysisPartition by criteria (e.g., by state) Partition by criteria (e.g., by state)

Separate row order in output from rankingSeparate row order in output from ranking

Paging using ROW_NUMBER functionPaging using ROW_NUMBER functionCommon scenario for walking through Common scenario for walking through result setsresult sets

Page 6: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

Ranking Function ScenarioData AnalysisRanking Function ScenarioData Analysis

SELECTSELECTRANK() OVER(ORDER BY City) as RANK,RANK() OVER(ORDER BY City) as RANK,RANK() OVER(PARTITION BY City ORDER BY RANK() OVER(PARTITION BY City ORDER BY LastName) as PART_RANK,LastName) as PART_RANK,DENSE_RANK() OVER(ORDER BY City) as DENSE_RANK() OVER(ORDER BY City) as DENSE_RANK, DENSE_RANK, ROW_NUMBER() OVER(ORDER BY City) as ROW_NUMBER() OVER(ORDER BY City) as ROW_NUM,ROW_NUM,NTILE(4) OVER(ORDER BY City) as NTILE_4,NTILE(4) OVER(ORDER BY City) as NTILE_4,LastName, LastName, FirstName, FirstName, City City

FROM Employees FROM Employees ORDER BY City, LastNameORDER BY City, LastName

Page 7: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

Ranking Function ScenarioData AnalysisRanking Function ScenarioData Analysis

1 11 1 1 1 11 11 LeverlingLeverling JanetJanet KirklandKirkland2 12 1 2 2 22 11 BuchananBuchanan StevenSteven LondonLondon2 22 2 2 2 55 22 DodsworthDodsworth AnneAnne LondonLondon2 32 3 2 2 44 22 KingKing RobertRobert LondonLondon2 42 4 2 2 33 11 SuyamaSuyama MichaelMichael LondonLondon6 16 1 3 3 66 33 PeacockPeacock MargaretMargaret RedmondRedmond7 17 1 4 4 88 44 CallahanCallahan LauraLaura Seattle Seattle 7 27 2 4 4 77 33 DavolioDavolio NancyNancy SeattleSeattle9 19 1 5 5 99 44 FullerFuller AndrewAndrew TacomaTacoma

RA

NK

RA

NK

PA

RT

_RA

NK

PA

RT

_RA

NK

DE

NS

E_R

AN

KD

EN

SE

_RA

NK

RO

W_N

UM

BE

RR

OW

_NU

MB

ER

NT

ILE

_4N

TIL

E_4

LastNameLastName FirstNameFirstName CityCity

Page 8: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

Ranking Function ScenarioPagingRanking Function ScenarioPaging

WITH OrderedOrders AS WITH OrderedOrders AS

(select SalesOrderID, OrderDate,(select SalesOrderID, OrderDate,

Row_Number() OVER (order by Row_Number() OVER (order by OrderDate) AS RN OrderDate) AS RN

from SalesOrderHeader ) from SalesOrderHeader )

SELECT * from OrderedOrders WHERE SELECT * from OrderedOrders WHERE RN between 50 and 60RN between 50 and 60

Display orders between 50 and 60 ordered by dateDisplay orders between 50 and 60 ordered by date

Page 9: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

New Relational Operators PIVOT/UNPIVOT/APPLYNew Relational Operators PIVOT/UNPIVOT/APPLY

PIVOTPIVOTTransforms a set of rows to columnsTransforms a set of rows to columnsSimilar to Access TRANSFORMSimilar to Access TRANSFORMUseful for open schemas/OLAP scenariosUseful for open schemas/OLAP scenarios

UNPIVOTUNPIVOTReverse operation of PIVOTReverse operation of PIVOT

APPLYAPPLYAllows evaluating a table-valued function for Allows evaluating a table-valued function for every row of outer-tableevery row of outer-tableAPPLY, CROSS APPLY, OUTER APPLYAPPLY, CROSS APPLY, OUTER APPLY

Page 10: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

New Relational OperatorsPIVOT exampleNew Relational OperatorsPIVOT example

MakeMake YearYear SalesSales

HondaHonda 19901990 20002000

HondaHonda 19901990 10001000

AcuraAcura 19901990 500500

HondaHonda 19911991 30003000

AcuraAcura 19911991 300300

AcuraAcura 19911991 600600

AcuraAcura 19921992 800800

SELECT * FROM CarSales SELECT * FROM CarSales PIVOT(SUM(PIVOT(SUM(SalesSales) FOR ) FOR YearYear IN ([1990], IN ([1990],[1991]))t [1991]))t

MakeMake 19901990 19911991HondaHonda 30003000 30003000

AcuraAcura 500500 900900

Page 11: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

New Relational OperatorsUNPIVOT exampleNew Relational OperatorsUNPIVOT example

MakeMake YearYear SalesSales

AcuraAcura 19901990 500500AcuraAcura 19911991 900900HondaHonda 19901990 30003000HondaHonda 19911991 30003000

select Make,t.Year,t.Sales select Make,t.Year,t.Sales from CarSalesPivot from CarSalesPivot UNPIVOTUNPIVOT((SalesSales for for YearYear in ([1990], in ([1990], [1991])) t[1991])) t

MakeMake 19901990 19911991

HondaHonda 30003000 30003000

AcuraAcura 500500 900900

Page 12: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

TOP (<expression>)TOP (<expression>)

SQL 7.0 and 2000 provided TOP (n) SQL 7.0 and 2000 provided TOP (n) with constant expressionwith constant expression

Yukon provides TOP (<expression>)Yukon provides TOP (<expression>)

Optimizer awareOptimizer aware

Page 13: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

Common Table ExpressionsCommon Table Expressions

As per SQL-99As per SQL-99

Common table expressionCommon table expressionWITH <CTEName> ( <col-list> ) AS ( <CTE>)WITH <CTEName> ( <col-list> ) AS ( <CTE>)

<SELECT, INSERT, UPDATE or DELETE using <SELECT, INSERT, UPDATE or DELETE using CTEname>CTEname>

The WITH clause together with the following The WITH clause together with the following SELECT/INSERT/DELETE/UPDATE is a single SELECT/INSERT/DELETE/UPDATE is a single statementstatement

Several CTEs may be defined in a single Several CTEs may be defined in a single T-SQL statement in the single WITH clauseT-SQL statement in the single WITH clause

Page 14: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

Common Table Expression (CTE) And RecursionCommon Table Expression (CTE) And Recursion

Main motivation for introducing CTE Main motivation for introducing CTE into SQL Server is recursioninto SQL Server is recursion

Collateral benefit – improve readability Collateral benefit – improve readability and manageability of complex SQL and manageability of complex SQL StatementsStatements

Similar to VIEWs and even more to Similar to VIEWs and even more to Derived TablesDerived Tables

Over time most of the CTEs will be used Over time most of the CTEs will be used for this purposefor this purpose

Page 15: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

Recursive Queries And CTERecursive Queries And CTE

Ability to traverse recursive hierarchies Ability to traverse recursive hierarchies in a single queryin a single query

Typical scenarios:Typical scenarios:Hierarchy in a table (MGRID-EMPID, Part-Hierarchy in a table (MGRID-EMPID, Part-Subpart)Subpart)

Find all employees reporting to a manager orFind all employees reporting to a manager or

Find all parts required to assemble a productFind all parts required to assemble a product

Page 16: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

Recursive CTE’sRecursive CTE’s

Recursive, when <CTE> references Recursive, when <CTE> references itselfitself

Recursive form of CTERecursive form of CTE<non-recursive SELECT><non-recursive SELECT>

UNION ALLUNION ALL

<SELECT referencing CTE><SELECT referencing CTE>

Recursion stops when 2Recursion stops when 2ndnd SELECT SELECT produces empty resultsproduces empty results

InitializeInitialize

AccumulateAccumulate

Page 17: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

Without Recursive QueriesWithout Recursive QueriesDECLARE @RowsAdded int

-- table variable to hold accumulated results DECLARE @reports TABLE (empid nchar(5) primary key, empname nvarchar(50) NOT NULL, mgrid nchar(5),

title nvarchar(30), processed tinyint default 0)

-- initialize @Reports with direct reports of the given employee INSERT @reports SELECT empid, empname, mgrid, title, 0 FROM employees WHERE empid = ‘12345’

SET @RowsAdded = @@rowcount

-- While new employees were added in the previous iteration WHILE @RowsAdded > 0 BEGIN /*Mark all employee records whose direct reports are going to be found in this iteration

with processed=1.*/ UPDATE @reports SET processed = 1 WHERE processed = 0

-- Insert employees who report to employees marked 1. INSERT @reports SELECT e.empid, e.empname, e.mgrid, e.title, 0 FROM employees e, @reports r WHERE e.mgrid=r.empid and e.mgrid <> e.empid and r.processed = 1

SET @RowsAdded = @@rowcount /*Mark all employee records whose direct reports have been found in this iteration.*/

UPDATE @reports SET processed = 2 WHERE processed = 1 END

Page 18: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

With Recursive QueriesWith Recursive QueriesWITH EmpCTE(empid, empname, mgrid)AS( SELECT empid, empname, mgrid FROM Employees WHERE empid = ‘12345’ UNION ALL SELECT E.empid, E.empname, E.mgrid FROM Employees AS E JOIN EmpCTE AS M ON E.mgrid = M.empid)SELECT * FROM EmpCTE

Page 19: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

Index ChangesIndex Changes

ALTER INDEXALTER INDEXModifies an existing table or view index (relational or XML) by Modifies an existing table or view index (relational or XML) by disabling, rebuilding, or reorganizing the index; or by setting disabling, rebuilding, or reorganizing the index; or by setting options on the indexoptions on the index

Index optionsIndex optionsALLOW_ROW_LOCKSALLOW_ROW_LOCKS

ALLOW_PAGE_LOCKS ALLOW_PAGE_LOCKS

MAXDOPMAXDOP

ONLINEONLINE

FunctionsFunctionsfn_indexinfo fn_indexinfo

fn_virtualindexstatsfn_virtualindexstats

Page 20: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

Online Index OperationsOnline Index Operations

Online index maintenanceOnline index maintenanceCreateCreate

RebuildRebuild

Reorganize (including BLOBs)Reorganize (including BLOBs)

DropDrop

Add or drop constraint (primary key, unique)Add or drop constraint (primary key, unique)

Fully parallelFully parallel

Online/offline are both supported Online/offline are both supported

Updates run somewhat slower during an Updates run somewhat slower during an online index operationonline index operation

Page 21: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

Indexed View ImprovementsIndexed View Improvements

Improved performance Improved performance Compilation time improved when there are a large number of indexed Compilation time improved when there are a large number of indexed viewsviewsIndexed view maintenance time improved in some cases for I/U/DIndexed view maintenance time improved in some cases for I/U/D

Extended set of indexable viewsExtended set of indexable viewsScalar aggregates (without GROUP BY)Scalar aggregates (without GROUP BY)Scalar UDFs (T-SQL, deterministic, no SQL, no external access)Scalar UDFs (T-SQL, deterministic, no SQL, no external access)

Improved query-to-indexed-view matchingImproved query-to-indexed-view matchingScalar expressions (e.g., computed column c=a+b in indexed view Scalar expressions (e.g., computed column c=a+b in indexed view matches a+b in submitted query)matches a+b in submitted query)Scalar aggregatesScalar aggregatesScalar UDFs Scalar UDFs Interval subsumption (e.g., QP knows “A between 10 and 20” includes Interval subsumption (e.g., QP knows “A between 10 and 20” includes answer of “A between 15 and 18”)answer of “A between 15 and 18”)Condition equivalence (e.g., “a>=b and c=10” is same as “c=10 and Condition equivalence (e.g., “a>=b and c=10” is same as “c=10 and b<=a”)b<=a”)

Page 22: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

XML ShowplanXML Showplan

Output showplan/stats profile information in XML Output showplan/stats profile information in XML formatformat

Use documented, versioned XML schema with more Use documented, versioned XML schema with more info than SQL 2000 textual or graphical formatsinfo than SQL 2000 textual or graphical formats

Delivered to the client as a single-value result set Delivered to the client as a single-value result set Can be stored in a tableCan be stored in a table

Can be processed in many waysCan be processed in many waysUsing XML technologies: XQuery (from within SQL Server), Using XML technologies: XQuery (from within SQL Server), XSLT, XPath, SAX, DOM, …XSLT, XPath, SAX, DOM, …

Programmatically: C#, C++, Java, …Programmatically: C#, C++, Java, …

Viewed using any XML toolViewed using any XML tool

Page 23: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

XML Showplan UsageXML Showplan Usageset showplan_xml onset showplan_xml on← ← your query goes here →your query goes here →set showplan_xml offset showplan_xml off

Output looks like:Output looks like:<ShowPlanXML xmlns=“http://www.microsoft.com/ .....><ShowPlanXML xmlns=“http://www.microsoft.com/ .....> <BatchSequence><BatchSequence> <Batch><Batch> <Statements><Statements>

<Statement><Statement> <StatementSetOptions …. /><StatementSetOptions …. /> <QueryPlan><QueryPlan> <RelOp NodeId=“0” PhysicalOp=“StreamAggregate” …><RelOp NodeId=“0” PhysicalOp=“StreamAggregate” …>

……… ……….. </RelOp></RelOp>

</QueryPlan></QueryPlan> </Statement></Statement>

</Statements></Statements> </Batch></Batch> </BatchSequence></BatchSequence></ShowPlanXML></ShowPlanXML>

Page 24: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

XML Showplan ExampleXML Showplan Example

Store XML showplans for your workload Store XML showplans for your workload in a SQL table, and write XQuery queries in a SQL table, and write XQuery queries against themagainst them

How often was the non-clustered index How often was the non-clustered index on table ITEMS used?on table ITEMS used?

Which query plans used merge join? Which query plans used merge join?

Can write a C# UDP to send a query to a Can write a C# UDP to send a query to a SQL Server, and get the XML Showplan SQL Server, and get the XML Showplan results in a T-SQL variable, process that results in a T-SQL variable, process that variable any way you wantvariable any way you want

Page 25: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

Table VariablesTable Variables

INSERT … EXECUTE now supported INSERT … EXECUTE now supported for Table Variablesfor Table Variables

Table Variables Column supportTable Variables Column supportAlias TypesAlias Types

.NET User Defined Types.NET User Defined Types

Page 26: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

Snapshot IsolationSnapshot Isolation

Transaction isolation levelsTransaction isolation levelsRead UncommittedRead Uncommitted

Read CommittedRead Committed

Repeatable ReadRepeatable Read

SerializableSerializable

SnapshotSnapshot

Page 27: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

Snapshot IsolationSnapshot Isolation

Increased data availability for Increased data availability for read applicationsread applications

Allows non-blocking consistent reads Allows non-blocking consistent reads in an OLTP environmentin an OLTP environmentWriters don’t block readersWriters don’t block readersReaders don’t block writersReaders don’t block writers

Permits writes, which can Permits writes, which can cause conflictscause conflicts

BUT…includes mandatory BUT…includes mandatory conflict detectionconflict detection

Page 28: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

Snapshot IsolationScenariosSnapshot IsolationScenarios

Business:Business:Reporting and ad-hoc queries running Reporting and ad-hoc queries running concurrently with OLTP concurrently with OLTP Read-mostly database with relatively few writesRead-mostly database with relatively few writesMigration from Oracle to SQL ServerMigration from Oracle to SQL Server

DBAs and Application Developers:DBAs and Application Developers:Consistent aggregates (e.g., AVG, SUM)Consistent aggregates (e.g., AVG, SUM)Index intersections and index joins without Index intersections and index joins without escalating read scans to a higher isolation level escalating read scans to a higher isolation level Deadlock reductionDeadlock reduction

Snapshot Isolation trades cost of concurrency (locking exclusion) Snapshot Isolation trades cost of concurrency (locking exclusion) for cost of CPU & I/O to construct transaction consistent viewfor cost of CPU & I/O to construct transaction consistent view

Page 29: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

Data TypesData Types

xmlxml

varchar(max)varchar(max)

nvarchar(max)nvarchar(max)

varbinary(max)varbinary(max)

Removed since Beta 1Removed since Beta 1Date, Time, UTCDateTimeDate, Time, UTCDateTime

Page 30: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

XML Data TypeXML Data Type

First class data type in T-SQLFirst class data type in T-SQLColumns, Variables, ParametersColumns, Variables, Parameters

Optionally constrained by XML SchemaOptionally constrained by XML SchemaData ManipulationData Manipulation

XQuery (W3C Standard) + DMLXQuery (W3C Standard) + DMLAbility to reference columns variables in XQueryAbility to reference columns variables in XQuery

XML IndexesXML IndexesCREATE TABLE Candidates (Id int, CREATE TABLE Candidates (Id int,

Resume XML)Resume XML)SELECT Id, Resume::Query(‘//Education’) SELECT Id, Resume::Query(‘//Education’) FROM CandidatesFROM Candidates

Page 31: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

varchar(max)varchar(max)

Extension to varchar, nvarchar, Extension to varchar, nvarchar, varbinary up to 2GBvarbinary up to 2GB

Uses MAX size specifierUses MAX size specifier

CREATE TABLE myTableCREATE TABLE myTable

(Id int, (Id int,

Picture varbinary(max))Picture varbinary(max))

Alternative to text/ntext/imageAlternative to text/ntext/imageNo text pointer supportNo text pointer support

Page 32: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

varchar(max)varchar(max)

Unified programming model for small and Unified programming model for small and large data typeslarge data types

ComparisonsComparisons

TriggersTriggers

ConcatenationConcatenation

AggregatesAggregates

ParametersParameters

VariablesVariables

Facilitates smooth transition when small Facilitates smooth transition when small string/binary data outgrows 8K limitstring/binary data outgrows 8K limit

Page 33: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

varchar(max)varchar(max)

All string functions operate on All string functions operate on varchar(max)varchar(max)

SUBSTRING used to read chunksSUBSTRING used to read chunks

UPDATE statement enhanced to UPDATE statement enhanced to support update of CHUNKSsupport update of CHUNKS

Example:Example:UPDATE myTableUPDATE myTableSET Picture::Write(@newchunk, @offset, SET Picture::Write(@newchunk, @offset, @remove)@remove)

Page 34: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

DRI ChangesDRI Changes

Support for New Declarative Referential Support for New Declarative Referential Integrity (DRI) Actions SET DEFAULT and Integrity (DRI) Actions SET DEFAULT and SET NULLSET NULL

ON DELETE SET NULL ON DELETE SET NULL

ON UPDATE SET NULL ON UPDATE SET NULL

ON DELETE SET DEFAULT ON DELETE SET DEFAULT

ON UPDATE SET DEFAULT ON UPDATE SET DEFAULT

ObjectPropertyObjectPropertyCnstIsDeleteCascade CnstIsDeleteCascade

CnstIsUpdateCascadeCnstIsUpdateCascade

Page 35: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

DML With OUTPUTDML With OUTPUT

OUTPUT clause for DMLOUTPUT clause for DML

Ability to return rows as part of DML operationsAbility to return rows as part of DML operations

Use “Inserted” and “Deleted” columns available to Use “Inserted” and “Deleted” columns available to get pre- and post-update valuesget pre- and post-update values

Option to store returned rowsOption to store returned rowsOUTPUT… INTO…OUTPUT… INTO…

Example:Example:UPDATE OrdersUPDATE OrdersSET status=’processed’SET status=’processed’OUTPUT DELETED.*, INSERTED.* OUTPUT DELETED.*, INSERTED.* WHERE status=‘unprocessed’WHERE status=‘unprocessed’

Page 36: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

DDL TriggersDDL Triggers

Extension of traditional triggers Extension of traditional triggers for DDL eventsfor DDL events

Triggering events include all DDL Triggering events include all DDL statementsstatements

CREATE_TABLE, ALTER_PROCEDURE, CREATE_TABLE, ALTER_PROCEDURE, DROP_LOGIN, etc.DROP_LOGIN, etc.

Scoping at Database and Server levelsScoping at Database and Server levels

Event data available inside trigger through Event data available inside trigger through eventdata() functioneventdata() function

Page 37: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

DDL Triggers ScenariosDDL Triggers Scenarios

Enforce development rules/standards Enforce development rules/standards for objects in a DBfor objects in a DB

Fail CREATE/ALTER if rule is violatedFail CREATE/ALTER if rule is violated

Protect from accidental dropsProtect from accidental drops

Object checkin/checkoutObject checkin/checkout

Source versioningSource versioning

Log management activityLog management activity

Page 38: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

Statement Level RecompileStatement Level Recompile

SQL Server 2000: Module-level compilation and SQL Server 2000: Module-level compilation and recompilationrecompilation

Module: sp, trigger, function, batch, etc.Module: sp, trigger, function, batch, etc.

SQL Server 2005: Module-level compilation, SQL Server 2005: Module-level compilation, statement level recompilationstatement level recompilation

Recompile statement only, not entire stored procedureRecompile statement only, not entire stored procedureAvoid blocking recompilation due to statistics updateAvoid blocking recompilation due to statistics update

If plan is sensitive to parameter values, can override sniffingIf plan is sensitive to parameter values, can override sniffing

TRY/CATCH support for catching errors in statement TRY/CATCH support for catching errors in statement level recompilationslevel recompilations

Page 39: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

T-SQL Exception HandlingT-SQL Exception Handling

TRY...CATCHTRY...CATCH

Beta 1 had Transaction Abort HandlingBeta 1 had Transaction Abort HandlingCatch Transaction Abort ErrorsCatch Transaction Abort Errors

““Doomed” TransactionsDoomed” Transactions

WITH TRAN_ABORT extension to RAISERRORWITH TRAN_ABORT extension to RAISERROR

Beta 2 and beyondBeta 2 and beyondCatch any error which sets @@errorCatch any error which sets @@error

Simplified TRY/CATCH syntaxSimplified TRY/CATCH syntax

Simplified RAISERROR syntaxSimplified RAISERROR syntax

Page 40: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

Exception HandlingException Handling

Syntax:Syntax:

BEGIN TRYBEGIN TRYsql statements…sql statements…

END TRYEND TRYBEGIN CATCHBEGIN CATCH

sql statements…sql statements…END CATCHEND CATCH

Page 41: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

Exception Handling – ErrorsException Handling – Errors

All errors that set @@error throw All errors that set @@error throw an exceptionan exception

Statement Abort ErrorsStatement Abort Errors

Level Abort ErrorsLevel Abort ErrorsIncludes Statement Level Includes Statement Level Recompilation ErrorsRecompilation Errors

Batch Abort ErrorsBatch Abort Errors

Tran Abort ErrorsTran Abort ErrorsTransaction DoomedTransaction Doomed

Page 42: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

Exception HandlingTRY/CATCH SemanticsException HandlingTRY/CATCH Semantics

TRY/CATCH constructs may be nestedTRY/CATCH constructs may be nested

Thrown exceptions are caught by the Thrown exceptions are caught by the CATCH block associated with the CATCH block associated with the closest compiled TRY/CATCH closest compiled TRY/CATCH constructconstruct

Page 43: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

Exception HandlingError DetailsException HandlingError Details

Error details are available at any time Error details are available at any time within the CATCH blockwithin the CATCH block

error_number()error_number()

error_message()error_message()Text with parametersText with parameters

error_severity()error_severity()

error_state()error_state()

Page 44: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

Exception Handling(Re)throwing an ExceptionException Handling(Re)throwing an Exception

RAISERROR raises real errors within RAISERROR raises real errors within the scope of a TRY or CATCH blockthe scope of a TRY or CATCH block

““Throws” within the scope of a TRY blockThrows” within the scope of a TRY block

To “Rethrow”To “Rethrow”Capture error details within the catch blockCapture error details within the catch block

Pass error details to RAISERRORPass error details to RAISERROR

Page 45: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

SummarySummary

SQL Server 2005 evolves T-SQL on SQL Server 2005 evolves T-SQL on a number of important aspects:a number of important aspects:

SQL Query Expressiveness and PowerSQL Query Expressiveness and Power

Procedural CapabilitiesProcedural Capabilities

Data TypesData Types

Improved parallelismImproved parallelism

Page 46: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

Visit the SQL Server 2005 website: Visit the SQL Server 2005 website: www.microsoft.com/sql/2005www.microsoft.com/sql/2005

Learn more about SQL Server 2005 at TechLearn more about SQL Server 2005 at TechEdEd Hands On Labs Hands On Labs

Rooms 6E and 6FRooms 6E and 6F 13 Hands On Labs13 Hands On Labs

Ask the Experts Ask the Experts Track Cabanas located around CommNetTrack Cabanas located around CommNet Experts Available All WeekExperts Available All Week

Next Steps: SQL Server 2005Next Steps: SQL Server 2005

Exclusive TechExclusive TechEd Offer!Ed Offer!Receive Receive Beta 2Beta 2 of of SQL Server 2005SQL Server 2005

Register for SQL Server 2005 Beta 2 at: Register for SQL Server 2005 Beta 2 at: http://www.msteched.com/SqlBetaBits.aspx

Exclusive TechExclusive TechEd Offer!Ed Offer!Receive Receive Beta 2Beta 2 of of SQL Server 2005SQL Server 2005

Register for SQL Server 2005 Beta 2 at: Register for SQL Server 2005 Beta 2 at: http://www.msteched.com/SqlBetaBits.aspx

Page 47: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

SQL Server 2005: SQL Server 2005: More SessionsMore Sessions

DAT330DAT330 Tue 3.30 – 4.45Tue 3.30 – 4.45 SQL Server 2005 (code named "Yukon"): Security EnhancementsSQL Server 2005 (code named "Yukon"): Security Enhancements

DAT329DAT329 Tue 5.00 – 6.15Tue 5.00 – 6.15 SQL Server 2005 (code named "Yukon"): A Platform for Web ServicesSQL Server 2005 (code named "Yukon"): A Platform for Web Services

DAT313DAT313 Wed 8.30 – 9.45Wed 8.30 – 9.45 Introducing SQL Server 2005 (code named "Yukon") Data Transformation ServicesIntroducing SQL Server 2005 (code named "Yukon") Data Transformation Services

DAT377DAT377 Wed 10.15 – 11.45Wed 10.15 – 11.45 Data mining in SQL Server 2000 and SQL Server 2005 (code named "Yukon")Data mining in SQL Server 2000 and SQL Server 2005 (code named "Yukon")

DAT317DAT317 Wed 2.00 – 3.15Wed 2.00 – 3.15 SQL Server 2005 (code named "Yukon"): Setup and DeploymentSQL Server 2005 (code named "Yukon"): Setup and Deployment

DAT318DAT318 Wed 3.45 – 5.00Wed 3.45 – 5.00 SQL Server 2005 (code named "Yukon"): .NET Framework-Based Programming in SQL Server 2005 (code named "Yukon"): .NET Framework-Based Programming in the Databasethe Database

DAT323DAT323 Wed 5.30 – 6.45Wed 5.30 – 6.45 SQL Server 2005 (code named "Yukon"): What's New in ReplicationSQL Server 2005 (code named "Yukon"): What's New in Replication

DAT328DAT328 Thu 8.30 – 9.45Thu 8.30 – 9.45 SQL Server 2005 (code named "Yukon"): Introduction to the Unified Dimensional SQL Server 2005 (code named "Yukon"): Introduction to the Unified Dimensional Model in Analysis ServicesModel in Analysis Services

DATC15DATC15 Thu 10.15 – 11.30Thu 10.15 – 11.30 Real Time Analytics: Bringing It All Together Using Analysis ServicesReal Time Analytics: Bringing It All Together Using Analysis Services

DAT321DAT321 Thu 10.15 – 11.30Thu 10.15 – 11.30 SQL Server 2005 (code named "Yukon"): Management ToolsSQL Server 2005 (code named "Yukon"): Management Tools

DAT319DAT319 Thu 1.30 – 2.45Thu 1.30 – 2.45 XML in the Database - the XML Data Type in SQL Server 2005 (code named "Yukon")XML in the Database - the XML Data Type in SQL Server 2005 (code named "Yukon")

DAT340DAT340 Thu 3.15 – 4.30Thu 3.15 – 4.30 Applying and Targeting DTS in SQL Server 2005 (Code Named "Yukon")Applying and Targeting DTS in SQL Server 2005 (Code Named "Yukon")

DAT324DAT324 Thu 5.00 – 6.15Thu 5.00 – 6.15 SQL Server 2005 (code named "Yukon"): Backup and Restore EngineSQL Server 2005 (code named "Yukon"): Backup and Restore Engine

DAT322DAT322 Fri 9.00 – 10.15Fri 9.00 – 10.15 SQL Server 2005 (code named "Yukon"): SQL Server Management Object (SMO), SQL Server 2005 (code named "Yukon"): SQL Server Management Object (SMO), Next Generation SQL-DMONext Generation SQL-DMO

DAT431DAT431 Fri 10.45 – 12.00Fri 10.45 – 12.00 High Availability Technologies in SQL Server 2000 and SQL Server 2005 (code High Availability Technologies in SQL Server 2000 and SQL Server 2005 (code named "Yukon"): A Comparative Studynamed "Yukon"): A Comparative Study

DAT326DAT326 Fri 10.45 – 12.00Fri 10.45 – 12.00 SQL Server 2005 (code named "Yukon"): Be More Efficient with T-SQLSQL Server 2005 (code named "Yukon"): Be More Efficient with T-SQL

DAT325DAT325 Fri 1.00 – 2.15Fri 1.00 – 2.15 SQL Server 2005 (code named "Yukon"): Using the Service Broker to Build SQL Server 2005 (code named "Yukon"): Using the Service Broker to Build Asynchronous, Queued Database ApplicationsAsynchronous, Queued Database Applications

DAT327DAT327 Fri 2.45 – 4.00Fri 2.45 – 4.00 SQL Server 2005 (code named "Yukon"): Inside XQuerySQL Server 2005 (code named "Yukon"): Inside XQuery

Page 48: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

SQL Server Community sitesSQL Server Community siteshttp://www.microsoft.com/http://www.microsoft.com/sql/community/default.mspxsql/community/default.mspx

List of newsgroupsList of newsgroupshttp://www.microsoft.com/sql/community/newsgroups/default.mspxhttp://www.microsoft.com/sql/community/newsgroups/default.mspx

Locate Local User GroupsLocate Local User Groupshttphttp://www.microsoft.com/communities/://www.microsoft.com/communities/usergroups/default.mspxusergroups/default.mspx

Attend a free chat or web castAttend a free chat or web casthttp://www.microsoft.com/communities/chats/default.mspxhttp://www.microsoft.com/communities/chats/default.mspx http://www.microsoft.com/usa/webcasts/default.asphttp://www.microsoft.com/usa/webcasts/default.asp

Page 49: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

Q1:Q1: Overall satisfaction with the sessionOverall satisfaction with the session

Q2:Q2: Usefulness of the informationUsefulness of the information

Q3:Q3: Presenter’s knowledge of the subjectPresenter’s knowledge of the subject

Q4:Q4: Presenter’s presentation skillsPresenter’s presentation skills

Q5:Q5: Effectiveness of the presentationEffectiveness of the presentation

Please fill out a session evaluation on CommNetPlease fill out a session evaluation on CommNet

Page 50: DAT326 SQL Server 2005 (Codenamed “Yukon”): Is T-SQL Dead? Gert E.R. Drapers Software Architect Microsoft Corporation

© 2004 Microsoft Corporation. All rights reserved.This presentation is for informational purposes only. Microsoft makes no warranties, express or implied, in this summary.