Vous êtes sur la page 1sur 35

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


AS
SELECT BusinessEntityID, JobTitle, HireDate,
VacationHours
FROM HumanResources.Employee;
GO

--Valid batch
INSERT INTO Production.UnitMeasure (Name,
UnitMeasureCode, ModifiedDate)
VALUES (N'Square Footage', NF4', GETDATE()),
(N'Square Inches', NI2', GETDATE());
GO
--Invalid batch
INSERT INTO dbo.t1 VALUE(1,2,N'abc');
INSERT INTO dbo.t1 VALUES(2,3,N'def');
GO

--Declare,initialize, and use a variable


DECLARE @SalesPerson_id INT = 5;
SELECT OrderYear, COUNT(DISTINCT CustomerID) AS
CustCount
FROM (
SELECT YEAR(OrderDate) AS OrderYear, CustomerID
FROM Sales.SalesOrderHeader
WHERE SalesPersonID = @SalesPerson_id
) AS DerivedYear
GROUP BY OrderYear;

--Declare and initialize variables


DECLARE @numrows INT = 3, @catid INT = 2;
--Use variables to pass parameters to
procedure
EXEC Production.ProdsByCategory
@numrows = @numrows, @catid = @catid;
GO

-- Create a synonym for the Product table in AdventureWorks


CREATE SYNONYM dbo.MyProduct
FOR AdventureWorks.Production.Product;
GO
-- Query the Product table by using the synonym.
SELECT ProductID, Name
FROM MyProduct
WHERE ProductID < 5;
GO

IF OBJECT_ID (Production.Product', 'U') IS NOT NULL


PRINT 'I am here and contain data, so dont delete me

IF OBJECT_ID (Production.Product', 'U') IS NOT NULL


PRINT 'I am here and contain data, so dont delete me
ELSE
PRINT Table not found, so feel free to create one
GO

DECLARE @BusinessEntID AS INT = 1, @Title AS


NVARCHAR(50);
WHILE @BusinessEntID <=10
BEGIN
SELECT @Title = JobTitle FROM
HumanResources.Employee
WHERE 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 TRY
BEGIN CATCH
SELECT
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 ErrorMessage


8134
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 TRY
BEGIN CATCH
SELECT
ERROR_NUMBER() AS ErrorNumber
,ERROR_MESSAGE() AS ErrorMessage;
END CATCH

Msg 208, Level 16, State 1, Line 4


Invalid object name IDontExist'.

BEGIN TRY
SELECT 100/0 AS 'Problem';
END TRY
BEGIN 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 management


BEGIN TRY
INSERT INTO Sales.SalesOrderHeader... --Insert succeeds
INSERT INTO Sales.SalesOrderDetail... --Insert fails
END TRY
BEGIN CATCH
--First row still in Sales.SalesOrderHeader Table
SELECT ERROR_NUMBER()
...
END CATCH;

BEGIN TRY
BEGIN TRANSACTION
INSERT INTO Sales.SalesOrderHeader... --Succeeds
INSERT INTO Sales.SalesOrderDetail... --Fails
COMMIT TRANSACTION -- If no errors, transaction completes
END TRY
BEGIN CATCH
--Inserted rows still exist in Sales.SalesOrderHeader
SELECT ERROR_NUMBER()
ROLLBACK TRANSACTION --Any transaction work undone
END CATCH;

BEGIN TRY
BEGIN TRANSACTION -- marks beginning of transaction
INSERT INTO Sales.SalesOrderHeader... -Completed
INSERT INTO Sales.SalesOrderDetail... -Completed
...

BEGIN TRY
BEGIN TRAN -- marks beginning of transaction
INSERT INTO Sales.SalesOrderHeader...
INSERT INTO Sales.SalesOrderDetail...
COMMIT TRAN -- mark the transaction as complete
END TRY

BEGIN CATCH
SELECT ERROR_NUMBER() --sample error handling
ROLLBACK TRAN
END CATCH;

SET XACT_ABORT ON;

IF OBJECT_ID (Production.Product', 'U') IS NOT NULL


PRINT 'I am here and contain data, so dont delete me
ELSE
PRINT Table not found, so feel free to create one
GO
BEGIN TRY
SELECT 100/0 AS 'Problem';
END TRY
BEGIN 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.

Vous aimerez peut-être aussi