+ All Categories
Home > Documents > 07 - Programming With T-SQL

07 - Programming With T-SQL

Date post: 06-Jul-2016
Category:
Upload: chowdhury-golam-kibria
View: 228 times
Download: 0 times
Share this document with a friend
Description:
How to write procedures with T-SQL
35
07 | Programming with T-SQL
Transcript
Page 1: 07 - Programming With T-SQL

07 | Programming with T-SQL

Page 2: 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

Page 3: 07 - Programming With T-SQL
Page 4: 07 - Programming With T-SQL
Page 5: 07 - Programming With T-SQL

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

Page 6: 07 - Programming With T-SQL

--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

Page 7: 07 - Programming With T-SQL

--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;

Page 8: 07 - Programming With T-SQL

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

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

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

Page 9: 07 - Programming With T-SQL

-- 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

Page 10: 07 - Programming With T-SQL
Page 11: 07 - Programming With T-SQL
Page 12: 07 - Programming With T-SQL

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

Page 13: 07 - Programming With T-SQL

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

Page 14: 07 - Programming With T-SQL

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;

Page 15: 07 - Programming With T-SQL
Page 16: 07 - Programming With T-SQL
Page 17: 07 - Programming With T-SQL
Page 18: 07 - Programming With T-SQL

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

Page 19: 07 - Programming With T-SQL

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.

Page 20: 07 - Programming With T-SQL

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'.

Page 21: 07 - Programming With T-SQL

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

Page 22: 07 - Programming With T-SQL
Page 23: 07 - Programming With T-SQL
Page 24: 07 - Programming With T-SQL

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

Page 25: 07 - Programming With T-SQL

--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;

Page 26: 07 - Programming With T-SQL

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;

Page 27: 07 - Programming With T-SQL

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

Page 28: 07 - Programming With T-SQL

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

Page 29: 07 - Programming With T-SQL

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

Page 30: 07 - Programming With T-SQL

SET XACT_ABORT ON;

Page 31: 07 - Programming With T-SQL
Page 32: 07 - Programming With T-SQL
Page 33: 07 - Programming With T-SQL

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

Page 34: 07 - Programming With T-SQL

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

Page 35: 07 - Programming With T-SQL

©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.


Recommended