![Page 1: Practical Uses and Optimization of New T-SQL Features in Microsoft SQL Server 2012 Tobias Ternstrom DBI308](https://reader036.vdocuments.site/reader036/viewer/2022062516/56649d9e5503460f94a87d60/html5/thumbnails/1.jpg)
Practical Uses and Optimization of New T-SQL Features in Microsoft SQL Server 2012 Tobias Ternstrom
DBI308
![Page 3: Practical Uses and Optimization of New T-SQL Features in Microsoft SQL Server 2012 Tobias Ternstrom DBI308](https://reader036.vdocuments.site/reader036/viewer/2022062516/56649d9e5503460f94a87d60/html5/thumbnails/3.jpg)
Agenda
Key generation
Calculations & Aggregations
Common tasks
Exceptions & Messages
![Page 4: Practical Uses and Optimization of New T-SQL Features in Microsoft SQL Server 2012 Tobias Ternstrom DBI308](https://reader036.vdocuments.site/reader036/viewer/2022062516/56649d9e5503460f94a87d60/html5/thumbnails/4.jpg)
Key generationUse cases:
Unique keys across multiple tablesCustomers & Employees ContactsClient-side/distributed-system key generationPrep files with related items for import
Options:GUIDsTable to manage the keysNEW: Sequences
Key generation
SQL Server 2012
![Page 5: Practical Uses and Optimization of New T-SQL Features in Microsoft SQL Server 2012 Tobias Ternstrom DBI308](https://reader036.vdocuments.site/reader036/viewer/2022062516/56649d9e5503460f94a87d60/html5/thumbnails/5.jpg)
Sequence Generators
New Database Object, similar to the IDENTITY propertySeparates number-generation from table/columnANSI SQL standard compliant implementation
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 …
![Page 6: Practical Uses and Optimization of New T-SQL Features in Microsoft SQL Server 2012 Tobias Ternstrom DBI308](https://reader036.vdocuments.site/reader036/viewer/2022062516/56649d9e5503460f94a87d60/html5/thumbnails/6.jpg)
Key generation in action
![Page 7: Practical Uses and Optimization of New T-SQL Features in Microsoft SQL Server 2012 Tobias Ternstrom DBI308](https://reader036.vdocuments.site/reader036/viewer/2022062516/56649d9e5503460f94a87d60/html5/thumbnails/7.jpg)
• 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
GUIDs
Pros
Cons
Separate table Sequences
![Page 8: Practical Uses and Optimization of New T-SQL Features in Microsoft SQL Server 2012 Tobias Ternstrom DBI308](https://reader036.vdocuments.site/reader036/viewer/2022062516/56649d9e5503460f94a87d60/html5/thumbnails/8.jpg)
Exceptions & Messages
Use cases:Send progress updates to the applicationLog eventsRaise & handle exceptions
Options:RAISERRORxp_logeventLogging tableNEW: THROW
Exceptions & Messages
SQL Server 2012
![Page 9: Practical Uses and Optimization of New T-SQL Features in Microsoft SQL Server 2012 Tobias Ternstrom DBI308](https://reader036.vdocuments.site/reader036/viewer/2022062516/56649d9e5503460f94a87d60/html5/thumbnails/9.jpg)
New error handling with THROW
THROW <number>, <message>, <state>;Always aborts the batchBatch aborts if not in SET XACT_ABORT ON where it transaction-abortsDoes not automatically use sys.messagesIs even spelled correctly!
re-THROWBEGIN CATCH …; THROW;END CATCH
![Page 10: Practical Uses and Optimization of New T-SQL Features in Microsoft SQL Server 2012 Tobias Ternstrom DBI308](https://reader036.vdocuments.site/reader036/viewer/2022062516/56649d9e5503460f94a87d60/html5/thumbnails/10.jpg)
Exceptions & messages in action
![Page 11: Practical Uses and Optimization of New T-SQL Features in Microsoft SQL Server 2012 Tobias Ternstrom DBI308](https://reader036.vdocuments.site/reader036/viewer/2022062516/56649d9e5503460f94a87d60/html5/thumbnails/11.jpg)
• Flexible• Well known
• Logs events without sending a message to the client
• Multiple behaviors, easy to get it wrong
• Not supported on SQL Azure
RAISERROR
Pros
Cons
xp_logevent
• Flexible, supports the attributes you specify
• Transactions need to be managed so log records are not rolled back
Logging table
• Easy to use• Similar behavior
to other programming languages
• Re-throw capabilities
• Less flexible than RAISERROR
THROW
![Page 12: Practical Uses and Optimization of New T-SQL Features in Microsoft SQL Server 2012 Tobias Ternstrom DBI308](https://reader036.vdocuments.site/reader036/viewer/2022062516/56649d9e5503460f94a87d60/html5/thumbnails/12.jpg)
Calculations & Aggregations
Use cases:Include aggregations in detailsCumulative sum, averages etc.Reference other rows in a calculationFinding gaps, trends, etc.
Options:Imperative programming patternsCorrelated sub queriesNEW: Window Functions
SQL Server 2012
Calculations & Aggregations
![Page 13: Practical Uses and Optimization of New T-SQL Features in Microsoft SQL Server 2012 Tobias Ternstrom DBI308](https://reader036.vdocuments.site/reader036/viewer/2022062516/56649d9e5503460f94a87d60/html5/thumbnails/13.jpg)
Calculations across rows
Referencing same row is simple:
Transaction cost is $1.5/tran., what was the total amount?
Amount + 1.5 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 1 2011-12-19 120
2 2 2011-12-20 500
3 3 2011-12-21 430
4 1 2011-12-26 95
5 2 2011-12-27 50
6 3 2011-12-28 25
7 1 2012-01-02 250
8 2 2012-01-03 25
9 3 2012-01-04 5000
10 1 2012-01-09 75
![Page 14: Practical Uses and Optimization of New T-SQL Features in Microsoft SQL Server 2012 Tobias Ternstrom DBI308](https://reader036.vdocuments.site/reader036/viewer/2022062516/56649d9e5503460f94a87d60/html5/thumbnails/14.jpg)
3 trn. avg.
Window Functions
Calculate the average amount of the last 3 transactions
TranId AccountId TranDate Amount
1 1 2011-12-19 120
2 2 2011-12-20 500
3 3 2011-12-21 430
4 1 2011-12-26 95
5 2 2011-12-27 50
6 3 2011-12-28 25
7 1 2012-01-02 250
8 2 2012-01-03 25
9 3 2012-01-04 5000
10 1 2012-01-09 75
120.000
310.000
350.000
341.666
191.666
56.666
108.333
100.000
1758.3331700.000
The FRAMEWindow
PARTITIONThe FRAMEThe FRAMEThe FRAMEThe FRAMEThe FRAMEThe FRAMEWindow FRAME
![Page 15: Practical Uses and Optimization of New T-SQL Features in Microsoft SQL Server 2012 Tobias Ternstrom DBI308](https://reader036.vdocuments.site/reader036/viewer/2022062516/56649d9e5503460f94a87d60/html5/thumbnails/15.jpg)
Window Functions
Multiple partitions, e.g. for calculating the balance for different accounts
Balance
TranId AccountId TranDate Amount
1 1 2011-12-19 120
4 1 2011-12-26 95
7 1 2012-01-02 250
10 1 2012-01-09 75
13 1 2012-01-16 125
16 1 2012-01-23 175
2 2 2011-12-20 500
5 2 2011-12-27 50
8 2 2012-01-03 25
11 2 2012-01-10 125
120
215
465
540
665
840
500
550
575
700
Window PARTITIONs
Window PARTITIONs
Window FRAMEWindow FRAME
![Page 16: Practical Uses and Optimization of New T-SQL Features in Microsoft SQL Server 2012 Tobias Ternstrom DBI308](https://reader036.vdocuments.site/reader036/viewer/2022062516/56649d9e5503460f94a87d60/html5/thumbnails/16.jpg)
Window Functions
AggregationAVG, CHECKSUM_AGG, COUNT, COUNT_BIG, MIN, MAX, SUM, STDEV, STDEVP, VAR, VARPUser-defined CLR Aggregates (excl. windowing)
AnalyticalROW_NUMBER, NTILE, RANK, DENSE_RANK, CUME_DIST, PERCENT_RANK
DistributionPERCENTILE_CONT, PERCENTILE_DISC
OffsetLAG, LEAD, FIRST_VALUE, LAST_VALUE
![Page 17: Practical Uses and Optimization of New T-SQL Features in Microsoft SQL Server 2012 Tobias Ternstrom DBI308](https://reader036.vdocuments.site/reader036/viewer/2022062516/56649d9e5503460f94a87d60/html5/thumbnails/17.jpg)
Calculations & Aggregations in action
![Page 18: Practical Uses and Optimization of New T-SQL Features in Microsoft SQL Server 2012 Tobias Ternstrom DBI308](https://reader036.vdocuments.site/reader036/viewer/2022062516/56649d9e5503460f94a87d60/html5/thumbnails/18.jpg)
• 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
Imperative approach
Pros
Cons
Correlated sub queries Window Functions
![Page 19: Practical Uses and Optimization of New T-SQL Features in Microsoft SQL Server 2012 Tobias Ternstrom DBI308](https://reader036.vdocuments.site/reader036/viewer/2022062516/56649d9e5503460f94a87d60/html5/thumbnails/19.jpg)
Common tasks
Use cases:Transform data to and from stringsConstructing date instancesHandle conversion errorsPaging
Options:Write yourselfNEW: Additional scalar functions
Common tasks
SQL Server 2012
![Page 20: Practical Uses and Optimization of New T-SQL Features in Microsoft SQL Server 2012 Tobias Ternstrom DBI308](https://reader036.vdocuments.site/reader036/viewer/2022062516/56649d9e5503460f94a87d60/html5/thumbnails/20.jpg)
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])
![Page 21: Practical Uses and Optimization of New T-SQL Features in Microsoft SQL Server 2012 Tobias Ternstrom DBI308](https://reader036.vdocuments.site/reader036/viewer/2022062516/56649d9e5503460f94a87d60/html5/thumbnails/21.jpg)
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)
![Page 22: Practical Uses and Optimization of New T-SQL Features in Microsoft SQL Server 2012 Tobias Ternstrom DBI308](https://reader036.vdocuments.site/reader036/viewer/2022062516/56649d9e5503460f94a87d60/html5/thumbnails/22.jpg)
Query Constructs / Dynamic SQL enhancements
OFFSET / FETCHSupport 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 ]}
![Page 23: Practical Uses and Optimization of New T-SQL Features in Microsoft SQL Server 2012 Tobias Ternstrom DBI308](https://reader036.vdocuments.site/reader036/viewer/2022062516/56649d9e5503460f94a87d60/html5/thumbnails/23.jpg)
Common tasks in action
![Page 24: Practical Uses and Optimization of New T-SQL Features in Microsoft SQL Server 2012 Tobias Ternstrom DBI308](https://reader036.vdocuments.site/reader036/viewer/2022062516/56649d9e5503460f94a87d60/html5/thumbnails/24.jpg)
Questions
?
![Page 25: Practical Uses and Optimization of New T-SQL Features in Microsoft SQL Server 2012 Tobias Ternstrom DBI308](https://reader036.vdocuments.site/reader036/viewer/2022062516/56649d9e5503460f94a87d60/html5/thumbnails/25.jpg)
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
![Page 26: Practical Uses and Optimization of New T-SQL Features in Microsoft SQL Server 2012 Tobias Ternstrom DBI308](https://reader036.vdocuments.site/reader036/viewer/2022062516/56649d9e5503460f94a87d60/html5/thumbnails/26.jpg)
Track Resources
@sqlserver@TechEd_europe
#msTechEd
mvaMicrosoft Virtual Academy
SQL Server 2012 Eval Copy
Get Certified!
Hands-On Labs
![Page 27: Practical Uses and Optimization of New T-SQL Features in Microsoft SQL Server 2012 Tobias Ternstrom DBI308](https://reader036.vdocuments.site/reader036/viewer/2022062516/56649d9e5503460f94a87d60/html5/thumbnails/27.jpg)
Resources
Connect. Share. Discuss.
http://europe.msteched.com
Learning
Microsoft Certification & Training Resources
www.microsoft.com/learning
TechNet
Resources for IT Professionals
http://microsoft.com/technet
Resources for Developers
http://microsoft.com/msdn
![Page 28: Practical Uses and Optimization of New T-SQL Features in Microsoft SQL Server 2012 Tobias Ternstrom DBI308](https://reader036.vdocuments.site/reader036/viewer/2022062516/56649d9e5503460f94a87d60/html5/thumbnails/28.jpg)
Evaluations
http://europe.msteched.com/sessions
Submit your evals online
![Page 29: Practical Uses and Optimization of New T-SQL Features in Microsoft SQL Server 2012 Tobias Ternstrom DBI308](https://reader036.vdocuments.site/reader036/viewer/2022062516/56649d9e5503460f94a87d60/html5/thumbnails/29.jpg)
© 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.
![Page 30: Practical Uses and Optimization of New T-SQL Features in Microsoft SQL Server 2012 Tobias Ternstrom DBI308](https://reader036.vdocuments.site/reader036/viewer/2022062516/56649d9e5503460f94a87d60/html5/thumbnails/30.jpg)