7a advanced tsql
Transcript of 7a advanced tsql
SQL Server 2008
Advanced TSQL
AgendaEnhancing DML Functionality
Output ClauseMerge Statement
Managing TransactionsImplicit TransactionExplicit Transaction
Exception HandlingTry…Catch
AgendaExtending SQL Server Functionality
CTEXMLCLRFileStreamSpatialFull Text SearchService Broker
AgendaApply Operator
Cross ApplyOuter Apply
Pivoting DataPIVOTUNPIVOT
Ranking FunctionsROW_NUMBERRANKDENSE_RANKNTILE
Output ClauseProvides ability to access INSERTED and
DELETED tables during DML statement execution as we can access in Triggers.
Output Example
Merge StatementProvides you the ability to compare rows
between source and target tables, and then performs DML action accordingly only on target Table.
Merge Example
Managing TransactionImplicit Transaction
Setting mode for implicit transactionManual Commit – Set Implicit_Transactions OFFAuto commit – Set Implicit_Transactions ON
Explicit TransactionBegin Transaction [Trans Name]Commit Transaction [Trans Name]Rollback Transaction [Trans Name]Savepoint – Save Transaction [Savepoint
name]
Exception Handling (Try..Catch)Captures Error severity higher that 10Try…Catch TSQLBegin Try
[SQL Statements]End TryBegin Catch
[SQL Statements]End Catch
Retrieving Error Information ERROR_NUMBER() returns the number of the error.
ERROR_SEVERITY() returns the severity.
ERROR_STATE() returns the error state number.
ERROR_PROCEDURE() returns the name of the stored procedure or trigger where the error occurred.
ERROR_LINE() returns the line number inside the routine that caused the error.
ERROR_MESSAGE() returns the complete text of the error message. The text includes the values supplied for any substitutable parameters, such as lengths, object names, or times.
Exception Handling
CTELike derived tablesIterates results setsRecursive
CTE PartsWith ClauseCTE NameColumn NamesAS keywordAnchor QueryUnion AllSecond QueryOuter Query
CTE;WITH cte(col1,col2..)AS(Anchor_QueryUnion AllSecond_Query)Outer_Query;
PIVOTING DATAMoving rows for a column as columns
for aggregate values, reversing that combination as well through unpivot
PartsSource TablePIVOT/UNPIVOT OperatorAggregationFilter Clause (FOR)Pivot Table
Pivot SyntaxFrom
(Subquery) AS Source_TablePIVOT (Aggregate_Function(Column_ST)FOR Column_ST IN (Values in Column_ST)) AS Pivot_Table
Apply OperatorOuter ApplyCross Apply