7a advanced tsql

17
SQL Server 2008 Advanced TSQL

Transcript of 7a advanced tsql

Page 1: 7a   advanced tsql

SQL Server 2008

Advanced TSQL

Page 2: 7a   advanced tsql

AgendaEnhancing DML Functionality

Output ClauseMerge Statement

Managing TransactionsImplicit TransactionExplicit Transaction

Exception HandlingTry…Catch

Page 3: 7a   advanced tsql

AgendaExtending SQL Server Functionality

CTEXMLCLRFileStreamSpatialFull Text SearchService Broker

Page 4: 7a   advanced tsql

AgendaApply Operator

Cross ApplyOuter Apply

Pivoting DataPIVOTUNPIVOT

Ranking FunctionsROW_NUMBERRANKDENSE_RANKNTILE

Page 5: 7a   advanced tsql

Output ClauseProvides ability to access INSERTED and

DELETED tables during DML statement execution as we can access in Triggers.

Page 6: 7a   advanced tsql

Output Example

Page 7: 7a   advanced tsql

Merge StatementProvides you the ability to compare rows

between source and target tables, and then performs DML action accordingly only on target Table.

Page 8: 7a   advanced tsql

Merge Example

Page 9: 7a   advanced tsql

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]

Page 10: 7a   advanced tsql

Exception Handling (Try..Catch)Captures Error severity higher that 10Try…Catch TSQLBegin Try

[SQL Statements]End TryBegin Catch

[SQL Statements]End Catch

Page 11: 7a   advanced tsql

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.

Page 12: 7a   advanced tsql

Exception Handling

Page 13: 7a   advanced tsql

CTELike derived tablesIterates results setsRecursive

CTE PartsWith ClauseCTE NameColumn NamesAS keywordAnchor QueryUnion AllSecond QueryOuter Query

Page 14: 7a   advanced tsql

CTE;WITH cte(col1,col2..)AS(Anchor_QueryUnion AllSecond_Query)Outer_Query;

Page 15: 7a   advanced tsql

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

Page 16: 7a   advanced tsql

Pivot SyntaxFrom

(Subquery) AS Source_TablePIVOT (Aggregate_Function(Column_ST)FOR Column_ST IN (Values in Column_ST)) AS Pivot_Table

Page 17: 7a   advanced tsql

Apply OperatorOuter ApplyCross Apply