Nuevas características del lenguaje T-SQL en SQL Server 2005

38
Nuevas características del lenguaje T-SQL en SQL Server 2005

description

Nuevas características del lenguaje T-SQL en SQL Server 2005. Adolfo Wiernik [email protected]. Microsoft Regional Director - http://msdn.microsoft.com/isv/rd Mentor Solid Quality Learning - http://www.solidqualitylearning.com Fundador, Costa Rica User Group .NET - http://www.crug.net - PowerPoint PPT Presentation

Transcript of Nuevas características del lenguaje T-SQL en SQL Server 2005

Page 1: Nuevas características del lenguaje T-SQL en  SQL Server 2005

Nuevas características del lenguaje T-SQL en SQL Server 2005

Page 2: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

2

Adolfo [email protected]

Microsoft Regional Director - http://msdn.microsoft.com/isv/rd Mentor Solid Quality Learning - http://www.solidqualitylearning.com Fundador, Costa Rica User Group .NET - http://www.crug.net Orador INETA Latinoamérica - http://www.ineta.org/latam Blog - http://www.wiernik.net

Jose Ricardo [email protected]

En Microsoft desde 1998 Desde el 2003 - Regional Program Manager SQL Server Latinoamérica

Page 3: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

3

Series de Webcasts Introducción a SQL Server 2005 para desarrolladores

Viernes, 22 de Julio de 2005 06:00 p.m.(GMT)http://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032277969&Culture=es-MX

Nuevas características del lenguaje T-SQL en SQL Server 2005Lunes, 25 de Julio de 2005 06:00 p.m.(GMT) http://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032277973&Culture=es-MX   

Aprovechando XML dentro de la base de datos con SQL Server 2005Viernes, 29 de Julio de 2005 06:00 p.m.(GMT) http://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032277975&Culture=es-MX

Programando SQL Server 2005 con el CLR – Integración SQL-CLRLunes, 01 de Agosto de 2005 06:00 p.m.(GMT) http://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032277977&Culture=es-MX  

Nuevas características en ADO.NET 2.0Viernes, 05 de Agosto de 2005 06:00 p.m.(GMT) http://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032277978&Culture=es-MX 

Page 4: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

4

.NET FrameworkCommon Language Runtime IntegrationUser-defined AggregatesUser-defined Data TypesUser-defined FunctionsSQL Server .NET Data ProviderExtended Triggers

Data TypesManaged SQL TypesNew XML DatatypeVarchar (MAX) Varbinary (MAX)

XMLXQUERY Support XML Data Manipulation Language FOR XML EnhancementsXML Schema (XSD) Support MSXML 6.0 (Native).Net XML Framework

Full-text SearchIndexing of XML Datatype

MDAC SNACMicrosoft Installer base setup

ADO.NET 2.0Notification SupportObject Model enhancements

SQL Client .NET Data ProviderServer Cursor SupportAsynchronous ExecutionSystem.Transactions

SecuritySeparation of Users and SchemaData encryption primitives

AdministrationSQL Management Objects (SMO)Analysis Management Objects

(AMO)Replication Management Objects

(RMO)T-SQL

Recursive QueriesCommon Table ExpressionsPIVOT – UNPIVOT OperatorsAPPLY OperatorException Handling

SQL Server EngineSQL Service BrokerHTTP Support (Native HTTP)Multiple Active Result Sets (MARS)Snapshot Isolation Level

Reporting ServicesMultiple Output Formats Parameters (Static, Dynamic,

Hierarchical)Bulk Delivery of Personalized

ContentSupport Multiple Data Sources STS (Web Parts, Doc Libraries)Visual Design ToolCharting, Sorting, Filtering, Drill-

ThroughScheduling, CachingComplete Scripting EngineScale Out architectureOpen XML Report Definition

Notification ServicesSQL Server Mobile Edition

Nuevas Características para Desarrollo

Page 5: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

5

Exception Handling Common Table Expressions (CTE) PIVOT Ranking and Partitioning Cross-Outer Apply TOP enhancements Auto output Large Objects (LOBs) Synonyms DDL Triggers

Agenda

Page 6: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

6

Handling exceptions SQL Server 2005 adds exception handling

• Error handling in previous SQL Server versions was tedious

• @@ERROR set on each statement• set variable with @@ERROR, then check value

• BEGIN-END TRY BEGIN-END CATCH blocks in SQL 2005

• semantic equivalent of BEGIN-END blocks• additional functions return error info• can query transaction status• can save @@ERROR

Page 7: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

7

Error handling functions New error information functions

• available inside catch block• ERROR_NUMBER() - number of the error• ERROR_SEVERITY() - severity• ERROR_STATE() - error state number• ERROR_MESSAGE() - complete text of the error message• ERROR_LINE() – line number that caused the error• ERROR_PROCEDURE() – name of the routine that cause the error

New transaction information function• operation that forced logic into catch block may cause un-commitable

transaction• XACT_STATE() – state of transaction

• 1 = transaction is active and valid• -1 = transaction is uncommittable• 0 = there is no transaction

Page 8: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

8

Exception handling example-- catch errors in a procedureCREATE PROCEDURE someprocASBEGIN BEGIN TRY SELECT * FROM authors END TRY BEGIN CATCH SELECT ERROR_NUMBER() END CATCHENDGO

-- catch errors in a batch BEGIN TRY SELECT * FROM authors END TRY BEGIN CATCH -- Test tx state IF (XACT_STATE()) = -1 ROLLBACK TRANSACTION IF (XACT_STATE()) = 1 COMMIT TRANSACTION END CATCHGO

Page 9: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

9

Common Table Expressions CTE is a temporary named resultset

• specified by starting query with a WITH keyword• can be replacement for subquery and used in view• can be used with SELECT/INSERT/UPDATE/DELETE

WITH mid AS(SELECT ((MAX(value) - MIN(value)) / 2) AS midval FROM invoices)SELECT CASE WHEN value > mid.midval THEN 0 ELSE 1 END AS half, invoices.* FROM invoices, mid ORDER BY half

categorize invoice by relative value

calculates median value

compares to median value

Page 10: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

10

Common Table Expression Syntax Common table expression starts with WITH clause

• expression in parentheses, preceded by name AS

Multiple common table expressions, comma separated Followed by SELECT statement

WITH low AS (SELECT ((MAX(amount)) / 3) AS v FROM invoices),high AS (SELECT (2 * MAX(amount) / 3) AS v FROM invoices)SELECT id, amount, amount - low.v FROM invoices, low, high WHERE invoices.amount > low.v AND invoices.amount <= high.v

first cte, named low

second cte, named high

SELECT statement

refers to high and low

common table expression syntax

Page 11: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

11

Common table expression execution CTE is evaluated only once

• less scans than subquery if used more than once

WITH low AS (SELECT ((max(amount)) / 3) AS v FROM invoices),high AS (SELECT (2 * max(amount) / 3) AS v FROM invoices)select id, amount, amount - low.v FROM invoices, low, high WHERE invoices.amount > low.v AND invoices.amount <= high.v

SELECT id, amount, amount - (SELECT (max(amount) / 3) FROM invoices) FROM invoices where amount > (SELECT (max(amount) / 3) FROM invoices) and amount < (SELECT (2 * max(amount) / 3) FROM invoices)

SELECT middle third of invoices

evaluated once

evaluatedtwice

Page 12: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

12

Recursive calculations Hierarchy may be of inconsistent depth

• chart of accounts and parts list are typical Calculations require traversal of hierarchy Many useful recursive calculations possible

• aggregates, e.g. sum of leaves is rollup value of account• leaves, e.g. bill of materials for parts list

recursive calculations

depth = 3

7 descendants

leaf 3 5

1

3 3

3

4 5 1

3

leaf value = 14

Page 13: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

13

Recursive common table expression Common table expression can do recursive calculation Recursive common table expression has three parts

• anchor, followed by UNION ALL; does initialization• recursive member after UNION ALL; recurses until no results• outer select; selects results to be returned

WITH descendant(parent, id, amount) AS(SELECT parent, id, amount FROM partsTree WHERE id = @startUNION ALLSELECT P.parent, P.id, P.amount FROM partsTree AS P INNER JOIN descendant AS A ON A.id = P.parent)SELECT id FROM descendant

anchor; executed once

recursive member; repeated

joined with previous recursion

outer select; id's returned

Page 14: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

14

Recursive query example

WITH descendant(parent, id, amount) AS(SELECT parent, id, amount FROM partsTree WHERE id = 2UNION ALLSELECT P.parent, P.id, P.amount FROM partsTree AS P INNER JOIN descendant AS A ON A.id = P.parent)SELECT id FROM descendant

id parent 1 NULL 2 NULL 3 2 4 2 5 3

2, 3, 4, 5

invoicestable

recursive commontable expression

select the cte

results

Page 15: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

15

Unknown properties Sometimes properties of products not known in advance

• paint has color, type, and amount; bolt has pitch, diameter

Every property has a name and value• one to many solution; one table for products, one for properties

Individual product tables sometimes needed

Page 16: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

16

Pivot Pivot turns columns into rows

• in effect it synthesizes a table

Widens table by adding columns to it• pivot can rotate many table from one to many solution

Page 17: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

17

Basic pivot Pivot needs three basic pieces of information

• columns that makeup rotated table• column that contains value for rotated table columns• pivot column, i.e. the many in the one to many relation

SELECT * FROM propertiesPIVOT (MAX(value)FOR name IN ([color], [type], [amount]))AS PWHERE id IN(SELECT id FROM products WHERE name='Swish')

make column wherename = one of these

pivot column

select only propertiesfor the Swish product

value column

Page 18: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

18

Basic pivot results Pivot selects all rows for a particular product Columns not mentioned in pivot used to group

properties

id color type amount-- ------- -------- -------1 blue oil 1 gal3 red latex 1 qt4 white oil 1 pt

pivoted properties of Swish product

id not mentionedin pivot expression

properties grouped by id

Page 19: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

19

Pivot and Unpivot The PIVOT keyword makes

• rows into columns and aggregates values• generates crosstab reports

UNPIVOT does the opposite• rotates columns to rows (not always symmetric w/PIVOT)

-- quantity by quarterCREATE TABLE quarterlysales( product varchar(50), quarter int, quantity int)GO

SELECT product, [1] AS 'Q1', [2] AS 'Q2', [3] AS 'Q3', [4] AS 'Q4' FROM quarterlysalesPIVOT(SUM(quantity) FOR quarter IN ([1], [2], [3], [4])) AS P

Page 20: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

20

Ranking and Windowing Functions

Adds a column to resultset based on ratings• ROW_NUMBER• RANK• DENSE_RANK• NTILE(n)

Page 21: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

21

Ordering

Column to be rated specified in ORDER BY clause• there must be at least one ordering column• can be more than one

SELECT orderid, customerid, ROW_NUMBER() OVER(ORDER BY orderid) AS num FROM ordersWHERE orderid < 10400AND customerid <= 'BN'

Page 22: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

22

Ranking Functions and Ties

Ties work differently in different functions• ROW_NUMBER – always unique• RANK – ties produce spaces and dups in

ranking• DENSE_RANK – dups but not ties• NTILE(n) – divided into n approximately equal

parts

Page 23: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

23

Duplicates and ties SELECT orderid, customerid, ROW_NUMBER() OVER(ORDER BY customerid) AS num, RANK() OVER(ORDER BY customerid) AS [rank], DENSE_RANK() OVER(ORDER BY customerid) AS [denserank], NTILE(5) OVER(ORDER BY customerid) AS ntile5FROM ordersWHERE orderid < 10400AND customerid <= 'BN'

orderid customerid num rank denserank tile5----------- ---------- ------ ------ --------- ------10308 ANATR 1 1 1 110365 ANTON 2 2 2 110355 AROUT 3 3 3 210383 AROUT 4 3 3 210278 BERGS 5 5 4 310280 BERGS 6 5 4 310384 BERGS 7 5 4 410265 BLONP 8 8 5 410297 BLONP 9 8 5 510360 BLONP 10 8 5 5

Page 24: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

24

Windowing

You can divide the resultset into subgroups• known as windows• use "PARITITION BY" in the OVER clause• each partition has its own ranking

Page 25: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

25

Windowing SELECT *, RANK() OVER(PARTITION BY COUNTRY ORDER BY age) AS [rank]from( SELECT lastname, country, DATEDIFF(yy,birthdate,getdate()) as age FROM employees) AS a

lastname country age rank-------------------- --------------- ----------- ------Dodsworth UK 37 1Suyama UK 40 2King UK 43 3Buchanan UK 48 4Leverling USA 40 1Callahan USA 45 2Fuller USA 51 3Davolio USA 55 4Peacock USA 66 5

Page 26: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

26

OVER and other aggregates

OVER can be used with other aggregates• includes user-defined aggregates• usually produces groups of duplicate values

Page 27: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

27

Over with max aggregate -- there is one oldest employee age for each countryselect *, RANK() OVER(PARTITION BY COUNTRY ORDER BY age) as [rank], MAX(age) OVER(PARTITION BY COUNTRY) as [oldest age in country]from( select lastname, country, datediff(yy,birthdate,getdate()) as age from employees) as a

lastname country age rank oldest age in country-------------------- --------------- ----------- ------ ----------Dodsworth UK 37 1 48Suyama UK 40 2 48King UK 43 3 48Buchanan UK 48 4 48Leverling USA 40 1 66Callahan USA 45 2 66Fuller USA 51 3 66Davolio USA 55 4 66Peacock USA 66 5 66

Page 28: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

28

Apply operators APPLY is join

• no ON clause allowed Right part can be any table, but meant for table UDF

• params for UDF can come from columns of left part Cross and outer apply available

SELECT * FROM invoice CROSS APPLY greater(amount, 1500)

SELECT I1.*, I2.amount FROM invoice I1 JOIN invoice I2 ON I2.amount > 1500 AND I2.id = I1.id

each invoice row joined to table returned by greater

equivalent join

function must return table

amount comes from invoice row

Page 29: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

29

Cross apply Cross apply does inner join

• no output for row when UDF produces no output• udf can get its parameters from LHS• useful when udf uses column from LHS

CREATE FUNCTION Greater(@v float, @t float) RETURNS TABLE AS RETURN SELECT @v AS v WHERE @v > @t

SELECT * FROM invoice CROSS APPLY Greater(invoice.amount, 1500)

returns either nothingor table with single row

returns rows from invoicewhere value > 1500

cross apply as filter

@v value frominvoice table

constant passedin for @t

Page 30: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

30

Outer apply OUTER APPLY does left outer join

• all rows from left part returned• may have NULLs for columns returned by UDF

CREATE FUNCTION greater(@v float, @t float) RETURNS TABLE AS RETURN SELECT @v AS v WHEN @v > @t

SELECT * from invoice OUTER APPLY greater(invoice.amount, 1500)

returns all rowsin invoice

Page 31: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

31

TOP query TOP query gets "first N" rows quickly

• first page of grid• TOP query can now be based on expression• update TOP N rows aids in batching updating

DECLARE @a int, @b int-- set @a and @b-- then, use expressionSELECT TOP (@a/@b) * FROM licenseGO

UPDATE TOP (3) license SET status = 'E' WHERE expire_date = getdate()GO

Page 32: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

32

OUTPUT clause on action statements

SQL action statements return "number of rows affected"• sometimes you want to know more• which rows were changed

• you could change from a static cursor to get this info

• what identity columns were generated• you could get @@ identity

• both cases require extra work to return info to caller

OUTPUT clause on actions generate output• returned through TABLE variables• no addition program logic needed• can use logical tables to return before/after images

Page 33: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

33

Returning automatic output -- output rows of "before" valuesDECLARE @tab TABLE (c1 ....)UPDATE orders SET shipregion = 'RJ' OUTPUT c.*, INSERTED.* into @tab FROM orders o JOIN customers c ON o.customerid=c.customeridGO

-- return default value and GUIDCREATE TABLE T ( id int, name varchar(20), a TIMESTAMP, b UNIQUEIDENTIFIER)GOINSERT T OUTPUT INSERTED.* into @tab -- table variable VALUES (1, 'bob', DEFAULT, NEWID()) GO

Page 34: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

34

Events include all DDL statements• CREATE_TABLE, ALTER_PROCEDURE,

DROP_LOGIN, etc. Scoping at Database and Server levels

• DDL_DATABASE_LEVEL_EVENTS Eventdata()

• Returns data regarding type of DDL event of type xml.

DDL Triggers

Page 35: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

35

Summary

T-SQL enhancements• exception handling added to T-SQL • most enhancements follow SQL-99 standard

• CTE, hierarchical CTE• PIVOT, ranking and partitioning (part 8 - OLAP)

• some enhance SQL Server specific functions• CROSS, OUTER APPLY• TOP• automatic output

• DDL Triggers

Page 36: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

36

Recursos SQL Server 2005 – Laboratorios Virtuales

http://msdn.demoservers.com/login.aspx?group=sql2005

http://www.microsoft.com/technet/traincert/virtuallab/sql.mspx(only supports SQL 2000)

SQL Server 2005http://www.microsoft.com/sql/2005

SQL Server Express http://www.microsoft.com/sql/express

Visual Studio 2005http://lab.msdn.microsoft.com/vs2005

Page 37: Nuevas características del lenguaje T-SQL en  SQL Server 2005

SQL Server 2005 para desarrolladores Solid Quality Learning

37

Series de Webcasts Introducción a SQL Server 2005 para desarrolladores

Viernes, 22 de Julio de 2005 06:00 p.m.(GMT)http://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032277969&Culture=es-MX

Nuevas características del lenguaje T-SQL en SQL Server 2005Lunes, 25 de Julio de 2005 06:00 p.m.(GMT) http://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032277973&Culture=es-MX   

Aprovechando XML dentro de la base de datos con SQL Server 2005Viernes, 29 de Julio de 2005 06:00 p.m.(GMT) http://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032277975&Culture=es-MX

Programando SQL Server 2005 con el CLR – Integración SQL-CLRLunes, 01 de Agosto de 2005 06:00 p.m.(GMT) http://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032277977&Culture=es-MX  

Nuevas características en ADO.NET 2.0Viernes, 05 de Agosto de 2005 06:00 p.m.(GMT) http://msevents.microsoft.com/CUI/EventDetail.aspx?EventID=1032277978&Culture=es-MX