Presentation is loading. Please wait.

Presentation is loading. Please wait.

Jan Engelsberg Program Manager, SQL Server

Similar presentations


Presentation on theme: "Jan Engelsberg Program Manager, SQL Server"— Presentation transcript:

1 Jan Engelsberg Program Manager, SQL Server
DBI308 Practical Uses and Optimization of New T-SQL Features in Microsoft SQL Server 2012 Jan Engelsberg Program Manager, SQL Server © 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.

2 Program Manager, SQL Server
Jan Engelsberg

3 Agenda Key generation Exceptions & Messages
Calculations & Aggregations Common tasks

4 Key generation Use cases: Options:
Unique keys across multiple tables Customers & Employees  Contacts Client-side/distributed-system key generation Prep files with related items for import Options: GUIDs Table to manage the keys NEW: Sequences Key generation SQL Server 2012

5 Sequence Generators CREATE SEQUENCE [ schema_name . ] sequence_name [ AS { <built_in_integer_type> | <user-defined_integer_type> } ] [ START WITH <constant> ] [ INCREMENT BY <constant> ] [ MINVALUE <constant> | NO MINVALUE ] [ MAXVALUE <constant> | NO MAXVALUE ] [ CYCLE | NO CYCLE ] [ CACHE [ <constant> ] | NO CACHE ] NEXT VALUE FOR [ schema_name . ] sequence_name [ OVER (<over_order_by_clause>) ] EXEC sp_sequence_get_range … New Database Object, similar to the IDENTITY property Separates number-generation from table/column ANSI SQL standard compliant implementation

6 Key generation in action

7 GUIDs Pros Cons Separate table Sequences
Guaranteed to be globally unique Can be made sequential Caveats! Cannot be guessed (when not sequential) Use any data type for keys (for ex. strings) Can guarantee a continuous range of values (no wholes) Including ranges Serializes number generation across transactions Supports all integer types, starting from TINYINT up to DECIMAL(38, 0) Supports range reservation Caching “knob” for performance tuning Large; requires 16 bytes storage Many systems don’t natively support GUIDs Causes fragmentation Sequential generation cannot be guaranteed even with NEWSEQUENTIALID() Access to the identifier is serialized across transactions Performance issue Not native RDBMS functionality, more code Cannot guarantee a continuous range of values E.g. can “lose” values because of dirty shutdowns or rollbacks

8 Exceptions & Messages Use cases: Options:
Send progress updates to the application Log events Raise & handle exceptions Options: RAISERROR xp_logevent Logging table NEW: THROW Exceptions & Messages SQL Server 2012

9 New error handling with THROW
THROW <number>, <message>, <state>; Always aborts the batch Batch aborts if not in SET XACT_ABORT ON where it transaction-aborts Does not automatically use sys.messages Is even spelled correctly! re-THROW BEGIN CATCH …; THROW; END CATCH

10 Exceptions & messages in action

11 RAISERROR THROW xp_logevent Logging table Pros Cons Flexible
Well known Easy to use Similar behavior to other programming languages Re-throw capabilities Logs events without sending a message to the client Flexible, supports the attributes you specify Cons Multiple behaviors, easy to get it wrong Less flexible than RAISERROR Not supported on SQL Azure Transactions need to be managed so log records are not rolled back

12 Calculations & Aggregations
Use cases: Include aggregations in details Cumulative sum, averages etc. Reference other rows in a calculation Finding gaps, trends, etc. Options: Imperative programming patterns Correlated sub queries NEW: Window Functions SQL Server 2012 Calculations & Aggregations

13 Calculations across rows
Referencing same row is simple: Transaction cost is $1.5/tran., what was the total amount? Amount AS TotalAmount What about other rows? Current bank balance? Current account balance? Number of days since last tran.? Amount of previous transaction? TranId AccountId TranDate Amount 1 120 2 500 3 430 4 95 5 50 6 25 7 250 8 9 5000 10 75

14 Window Functions Calculate the average amount of the last 3 transactions TranId AccountId TranDate Amount 1 120 2 500 3 430 4 95 5 50 6 25 7 250 8 9 5000 10 75 3 trn. avg. Window FRAME The FRAME The FRAME The FRAME The FRAME The FRAME The FRAME The FRAME Window PARTITION 56.666

15 Window Functions Multiple partitions, e.g. for calculating the balance for different accounts TranId AccountId TranDate Amount 1 120 4 95 7 250 10 75 13 125 16 175 2 500 5 50 8 25 11 Balance 120 215 465 540 Window FRAME Window FRAME Window PARTITIONs 665 840 500 550 575 700

16 Window Functions Aggregation Analytical Distribution Offset
AVG, CHECKSUM_AGG, COUNT, COUNT_BIG, MIN, MAX, SUM, STDEV, STDEVP, VAR, VARP User-defined CLR Aggregates (excl. windowing) Analytical ROW_NUMBER, NTILE, RANK, DENSE_RANK, CUME_DIST, PERCENT_RANK Distribution PERCENTILE_CONT, PERCENTILE_DISC Offset LAG, LEAD, FIRST_VALUE, LAST_VALUE

17 Calculations & Aggregations in action

18 Correlated sub queries Window Functions
Imperative approach Pros Cons Correlated sub queries Window Functions Approach that is commonly used in other programming languages Follows the SQL set based paradigm Improved optimization Easy to write Following the SQL set based paradigm Not set based Only individual queries are optimized, not the operation as a whole Many lines of code  Higher risk for bugs Bad performance due to plan with N2 complexity solution Non-trivial to write Not always the optimal solution Not all queries can be easily rewritten to leverage window functions

19 Common tasks Use cases: Options: Transform data to and from strings
Constructing date instances Handle conversion errors Paging Options: Write yourself NEW: Additional scalar functions SQL Server 2012 Common tasks

20 New Scalar Functions New conversion functions for all types:
TRY_CONVERT(data_type[(length)], expression [,style]) TRY_CAST(expression AS data_type[(length)]) New conversion functions to and from strings: FORMAT(value, format [,culture]) PARSE(string_value AS data_type [USING culture]) TRY_PARSE(string_value AS data_type [USING culture]) Other functions: IIF(boolean_expr, true_value, false_value) CHOOSE(index, val1, val2,... [,valN]) CONCAT(val1, val2,… [,val N])

21 New Scalar Functions New date & time related functions:
EOMONTH(date [, months_to_add]) DATEFROMPARTS(year, month, day) TIMEFROMPARTS(hour, minutes, seconds, fractions, scale) DATETIME2FROMPARTS(year, month, day ,hour, minutes, seconds, fractions, scale) DATETIMEFROMPARTS(year, month, day, hour, minutes, seconds, milliseconds) SMALLDATETIMEFROMPARTS(year, month, day, hour, minutes) DATETIMEOFFSETFROMPARTS (year, month, day, hour, minute, seconds, fractions, hour_offset, minute_offset, precision)

22 Query Constructs / Dynamic SQL enhancements
OFFSET / FETCH Support for paging result sets Enforce contract for Result Sets for EXEC SELECT ... ORDER BY ... OFFSET <expr> ROWS FETCH NEXT <expr> ROWS ONLY EXECUTE <proc|clr proc|remote proc|function> [WITH <execute_option>[,...n ]] { RESULT SETS {UNDEFINED|NONE|(<result_sets_definition>)} } <result_sets_definition> ::= { <result_set_definition> | AS OBJECT [<object_location>.] {table_name | view_name | tvf} | AS TYPE [schema_name.]table_type_name | AS FOR XML | (…) [,...n ]}

23 Common tasks in action

24 Questions ?

25 Related Content (DBI311) Microsoft SQL Server Data Tools: Database Development from Zero to Sixty (DBI409)SQL Server Columnstore Performance Tuning (DBI21-HOL ) What's New in T-SQL for Microsoft SQL Server 2012 (DBI31-HOL) Getting Started with SQL Server Data Tools in Microsoft SQL Server 2012 (DBI07-TLC ) Microsoft SQL Server: Cloud on Your Terms - Optimized Productivity Find me in the TLC area at: 7:30 to 9p, Tuesday 10:30a to 1p, Wednesday 12:30 to 3:30p

26 mva Track Resources SQL Server 2012 Eval Copy Hands-On Labs @sqlserver
@ms_teched mva Microsoft Virtual Academy Get Certified!

27 Resources Learning TechNet http://northamerica.msteched.com
Connect. Share. Discuss. Microsoft Certification & Training Resources TechNet Resources for IT Professionals Resources for Developers

28 Complete an evaluation on CommNet and enter to win!
Required Slide Complete an evaluation on CommNet and enter to win!

29 MS Tag Scan the Tag to evaluate this session now on myTechEd Mobile
Required Slide *delete this box when your slide is finalized Your MS Tag will be inserted here during the final scrub. MS Tag Scan the Tag to evaluate this session now on myTechEd Mobile

30 11/24/ :06 AM © 2012 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. © 2009 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.

31 11/24/ :06 AM © 2009 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 "Jan Engelsberg Program Manager, SQL Server"

Similar presentations


Ads by Google