Practical uses of new T-SQL functionality in SQL Server 2012 & Windows Azure SQL Database
CREATE SEQUENCE [ schema_name. ] sequence_name [ AS { } ] [ START WITH ] [ INCREMENT BY ] [ MINVALUE | NO MINVALUE ] [ MAXVALUE | NO MAXVALUE ] [ CYCLE | NO CYCLE ] [ CACHE [ ] | NO CACHE ] NEXT VALUE FOR [ schema_name. ] sequence_name [ OVER ( ) ] EXEC sp_sequence_get_range …
Guaranteed to be globally unique Can be made sequential Caveats! Really hard to guess… (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 tableSequences
THROW,, ; 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
Flexible Well known Logs events without sending a message to the client Multiple behaviors, easy to get it wrong Not supported on SQL Database 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
TranIdAccountIdTranDateAmount
3 trn. avg. TranIdAccountIdTranDateAmount The FRAME Window PARTITION The FRAME Window FRAME
BalanceTranIdAccountIdTranDateAmount Window PARTITIONs The FRAME Window FRAME
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 N 2 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 queriesWindow Functions
SELECT... ORDER BY... OFFSET ROWS FETCH NEXT ROWS ONLY EXECUTE [WITH [,...n ]] { RESULT SETS {UNDEFINED|NONE|( )} } ::= { | AS OBJECT [.] {table_name | view_name | tvf} | AS TYPE [schema_name.]table_type_name | AS FOR XML | (…) [,...n ]}
Questions?