07 - Programming With T-SQL

Post on 06-Jul-2016

254 views 0 download

description

How to write procedures with T-SQL

Transcript of 07 - Programming With T-SQL

07 | Programming with T-SQL

Querying Microsoft SQL Server 2012 Jump Start

05 | SET Operators, Windows Functions, and Grouping

SET operators, Windows functions, GROUPING sets (PIVOT, UNPIVOT, CUBE, ROLLUP)

06 | Modifying Data INSERT, UPDATE, and DELETE statements, use of defaults, constraints, and triggers, OUTPUT

07 | Programming with T-SQL Using T-SQL programming elements, implementing error handling, understanding and implementing transactions

08 | Retrieving SQL Server Metadata and Improving Query Performance Querying system catalogs and dynamic management views, creating and executing stored procedures, improving SQL

Server query performance

CREATE VIEW HumanResources.EmployeeListASSELECT BusinessEntityID, JobTitle, HireDate, VacationHoursFROM HumanResources.Employee;GO

--Valid batchINSERT INTO Production.UnitMeasure (Name, UnitMeasureCode, ModifiedDate)VALUES (N'Square Footage', N‘F4', GETDATE()),

(N'Square Inches', N‘I2', GETDATE());GO--Invalid batchINSERT INTO dbo.t1 VALUE(1,2,N'abc');INSERT INTO dbo.t1 VALUES(2,3,N'def');GO

--Declare,initialize, and use a variableDECLARE @SalesPerson_id INT = 5;SELECT OrderYear, COUNT(DISTINCT CustomerID) ASCustCountFROM (SELECT YEAR(OrderDate) AS OrderYear, CustomerIDFROM Sales.SalesOrderHeaderWHERE SalesPersonID = @SalesPerson_id) AS DerivedYearGROUP BY OrderYear;

--Declare and initialize variablesDECLARE @numrows INT = 3, @catid INT = 2;

--Use variables to pass parameters to procedureEXEC Production.ProdsByCategory

@numrows = @numrows, @catid = @catid;GO

-- Create a synonym for the Product table in AdventureWorksCREATE SYNONYM dbo.MyProductFOR AdventureWorks.Production.Product;GO-- Query the Product table by using the synonym. SELECT ProductID, Name FROM MyProductWHERE ProductID < 5; GO

IF OBJECT_ID (‘Production.Product', 'U') IS NOT NULLPRINT 'I am here and contain data, so don’t delete me’

IF OBJECT_ID (‘Production.Product', 'U') IS NOT NULLPRINT 'I am here and contain data, so don’t delete me’

ELSEPRINT ‘Table not found, so feel free to create one’

GO

DECLARE @BusinessEntID AS INT = 1, @Title ASNVARCHAR(50);WHILE @BusinessEntID <=10

BEGINSELECT @Title = JobTitle FROM

HumanResources.EmployeeWHERE BusinessEntityID =

@BusinessEntID;PRINT @Title;SET @BusinessEntID += 1;

END;

Property Function to Query Description

Number ERROR_NUMBER Unique number assigned to

the error

Message ERROR_MESSAGE Error message text

Severity ERROR_SEVERITY Severity class (1-25)

Procedure Name ERROR_PROCEDURE Name of the procedure or

trigger that raised the error

Line Number ERROR_LINE Number of the line that

raised the error in the batch,

procedure, trigger, or function

BEGIN TRY-- Generate a divide-by-zero error.

SELECT 1/0;END TRYBEGIN CATCHSELECT

ERROR_NUMBER() AS ErrorNumber,ERROR_SEVERITY() AS ErrorSeverity,ERROR_STATE() AS ErrorState,ERROR_PROCEDURE() AS ErrorProcedure,ERROR_LINE() AS ErrorLine,ERROR_MESSAGE() AS ErrorMessage;

END CATCH;GO

ErrorNumber ErrorSeverity ErrorState ErrorProcedure ErrorLine ErrorMessage8134 16 1 NULL 3 Divide by zero

error encountered.

BEGIN TRY-- Table does not exist; object name resolution-- error not caught.

SELECT * FROM IDontExist;END TRYBEGIN CATCH

SELECT ERROR_NUMBER() AS ErrorNumber

,ERROR_MESSAGE() AS ErrorMessage;END CATCH

Msg 208, Level 16, State 1, Line 4Invalid object name ‘IDontExist'.

BEGIN TRYSELECT 100/0 AS 'Problem';

END TRYBEGIN CATCH

PRINT 'Code inside CATCH is beginning'PRINT ‘MyError: ' + CAST(ERROR_NUMBER()

AS VARCHAR(255));THROW;

END CATCH

--Two tasks that make up a unit of work INSERT INTO Sales.SalesOrderHeader...INSERT INTO Sales.SalesOrderDetail...

--Batch without transaction managementBEGIN TRYINSERT INTO Sales.SalesOrderHeader... --Insert succeedsINSERT INTO Sales.SalesOrderDetail... --Insert failsEND TRYBEGIN CATCH--First row still in Sales.SalesOrderHeader TableSELECT ERROR_NUMBER()...END CATCH;

BEGIN TRYBEGIN TRANSACTIONINSERT INTO Sales.SalesOrderHeader... --SucceedsINSERT INTO Sales.SalesOrderDetail... --Fails

COMMIT TRANSACTION -- If no errors, transaction completesEND TRYBEGIN CATCH--Inserted rows still exist in Sales.SalesOrderHeaderSELECT ERROR_NUMBER()ROLLBACK TRANSACTION --Any transaction work undoneEND CATCH;

BEGIN TRYBEGIN TRANSACTION -- marks beginning of transactionINSERT INTO Sales.SalesOrderHeader... –-CompletedINSERT INTO Sales.SalesOrderDetail... –-Completed...

BEGIN TRYBEGIN TRAN -- marks beginning of transactionINSERT INTO Sales.SalesOrderHeader...INSERT INTO Sales.SalesOrderDetail...COMMIT TRAN -- mark the transaction as completeEND TRY

BEGIN CATCHSELECT ERROR_NUMBER() --sample error handlingROLLBACK TRANEND CATCH;

SET XACT_ABORT ON;

IF OBJECT_ID (‘Production.Product', 'U') IS NOT NULLPRINT 'I am here and contain data, so don’t delete me’

ELSEPRINT ‘Table not found, so feel free to create one’

GO

BEGIN TRYSELECT 100/0 AS 'Problem';

END TRYBEGIN CATCH

PRINT 'Code inside CATCH is beginning'PRINT ‘MyError: ' + CAST(ERROR_NUMBER()

AS VARCHAR(255));THROW;

END CATCH

A transaction is a group of tasks defined as a unit of work that must succeed

or fail together. Blocks of code must succeed or fail together and provide

points where the database engine can roll back, or undo some operations

that occurred

You should use the following commands to manage your transactions:

BEGIN TRANSACTION

COMMIT TRANSACTION

ROLLBACK TRANSACTION

XACT_ABORT

©2013 Microsoft Corporation. All rights reserved. Microsoft, Windows, Office, Azure, System Center, Dynamics 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.