Download as ppt, pdf, or txt
Download as ppt, pdf, or txt
You are on page 1of 43

T-SQL Basics

Transact-SQL Overview

Transact-SQL Overview
Elements of Transact-SQL
• Data Control Language Statements
• Data Definition Language Statements
• Data Manipulation Language Statements
• SQL Server Object Names
• Naming Guidelines
Data Control Language Statements
• Set or Change Permissions
– GRANT
– DENY
– REVOKE
• By Default, Only sysadmin, dbcreator, db_owner, and
db_securityadmin Roles Can Execute
Data Definition Language Statements
• Define the Database Objects
– CREATE object_type object_name
– ALTER object_type object_name
– DROP object_type object_name
DML Statements
• Use When Working with Data in the Database
– SELECT
– INSERT
– UPDATE
– DELETE
SQL Server Object Names
• Standard Identifiers
– First character must be alphabetic
– Other characters can include letters, numerals, or symbols
– Identifiers starting with symbols have special uses
• Delimited Identifiers
– Use when names contain embedded spaces
– Use when reserved words are portions of names
– Enclose in brackets ([ ]) or quotation marks (" ")
Naming Guidelines
• Use Meaningful Names Where Possible
• Keep Names Short
• Use a Clear and Simple Naming Convention
• Chose an Identifier That Distinguishes Types of
Objects
– Views
– Stored procedures

• Keep Object Names and User Names Unique


Additional Language Elements
• Local Variables
• Operators
• Control of Flow Language Elements
• Comments
Local Variables
• DECLARE Statement
• Assigned Values with SET or Select Statement

DECLARE
DECLARE @vLastName
@vLastName char(20),
char(20),
@vFirstName
@vFirstName varchar(11)
varchar(11)
SET
SET @vLastName
@vLastName == 'Dodsworth'
'Dodsworth'
SELECT
SELECT @vFirstName
@vFirstName == FirstName
FirstName
FROM
FROM Northwind..Employees
Northwind..Employees
WHERE
WHERE LastName
LastName == @vLastName
@vLastName
PRINT
PRINT @vFirstName
@vFirstName ++ '' '' ++ @vLastName
@vLastName
GO
GO
Table Variable
• Is a special data type that can be used to store a result set for
processing later.
• Table variable is primarily used for temporary storage of a set of
rows returned as the result set of a table-valued function.
• Table variables are stored in main memory
• Example:
– DECLARE @MyTableVar table( EmpID int NOT NULL, OldVacationHours int,
NewVacationHours int, ModifiedDate datetime);
Temporary Tables
• Only for temporary storage
• Temporary tables gets stored in tempdb
• Example:
• CREATE TABLE #Yaks ( YakID int, YakName char(30) )
Cursors
• Cursor is a database object used by applications to manipulate data
in a set on a row-by-row basis, instead of the typical SQL
commands that operate on all the rows in the set at one time
• In most of the scenarios we can remove the usage of cursors and
use while loop with temporary tables to improve the performance.
Operators
• Types of Operators
– Arithmetic
– Comparison
– String concatenation
– Logical
• Operator Precedence Levels
Control of Flow Language Elements
• Statement Level
– BEGIN…END blocks
– IF…ELSE blocks
– WHILE constructs IF
IF USER_NAME()
USER_NAME() <><> 'dbo'
'dbo'
BEGIN
BEGIN
• Row Level RAISERROR('Must
RAISERROR('Must be be sysadmin
sysadmin
– CASE expression to Perform Operation',
to Perform Operation',
10,
10, 1)
1)
RETURN
RETURN
END
END
ELSE
ELSE
DBCC
DBCC CHECKDB(Northwind)
CHECKDB(Northwind)
Using Transactions
• Processed Like a Batch
• Data Integrity Is Guaranteed
• Changes to the Database Are Either Applied Together
or Rolled Back

BEGIN
BEGIN TRANSACTION
TRANSACTION
UPDATE
UPDATE savings
savings SET
SET amount
amount == (amount
(amount -- 100)
100)
WHERE
WHERE custid
custid == 78910
78910
…… <Rollback
<Rollback transaction
transaction if
if error>
error>
UPDATE
UPDATE checking
checking SET
SET amount
amount == (amount
(amount ++ 100)
100)
WHERE
WHERE custid
custid == 78910
78910
…… <Rollback
<Rollback transaction
transaction if
if error>
error>
COMMIT
COMMIT TRANSACTION
TRANSACTION
Triggers

Triggers
What is a Trigger?
• Associated with a Table
• Invoked Automatically
• Cannot Be Called Directly
• Is Part of a Transaction
Uses of Triggers
• Cascade Changes Through Related Tables in
a Database
• Enforce More Complex Data Integrity Than a
CHECK Constraint
• Define Custom Error Messages
• Maintain Denormalized Data
• Compare Before and After States of Data Under Modification
Considerations for Using Triggers
• Triggers Are Reactive; Constraints Are Proactive
• Constraints Are Checked First
• Tables Can Have Multiple Triggers for Any Action
• Table Owners Can Designate the First and Last Trigger to Fire
• You Must Have Permission to Perform All Statements That
Define Triggers
• Table Owners Cannot Create AFTER Triggers on Views or
Temporary Tables
Defining Triggers
• Creating Triggers
• Altering and Dropping Triggers
Creating Triggers

• Requires Appropriate Permissions


• Cannot Contain Certain Statements

Use
Use Northwind
Northwind
GO
GO
CREATE
CREATE TRIGGER
TRIGGER Empl_Delete
Empl_Delete ONON Employees
Employees
FOR DELETE
FOR DELETE
AS
AS
IF
IF (SELECT
(SELECT COUNT(*)
COUNT(*) FROM
FROM Deleted)
Deleted) >> 11
BEGIN
BEGIN
RAISERROR(
RAISERROR(
'You
'You cannot
cannot delete
delete more
more than
than one
one employee
employee at
at aa time.',
time.', 16,
16, 1)
1)
ROLLBACK TRANSACTION
ROLLBACK TRANSACTION
END
END
Altering and Dropping Triggers
• Altering a Trigger
– Changes the definition without dropping the trigger
– Can disable or enable a trigger

USE
USE Northwind
Northwind
GO
GO
ALTER
ALTER TRIGGER
TRIGGER Empl_Delete
Empl_Delete ONON Employees
Employees
FOR DELETE
FOR DELETE
AS
AS
IF
IF (SELECT
(SELECT COUNT(*)
COUNT(*) FROM
FROM Deleted)
Deleted) >> 66
BEGIN • Dropping a Trigger
BEGIN
RAISERROR(
RAISERROR(
'You
'You cannot
cannot delete
delete more
more than
than six
six employees
employees at
at aa time.',
time.', 16,
16, 1)
1)
ROLLBACK TRANSACTION
ROLLBACK TRANSACTION
END
END
How Triggers Work
• How an INSERT Trigger Works
• How a DELETE Trigger Works
• How an UPDATE Trigger Works
• How an INSTEAD OF Trigger Works
• How Nested Triggers Work
• Recursive Triggers
How an INSERT Trigger Works
INSERT statement to a table with an INSERT Trigger Defined
TRIGGER Actions Execute
INSERT
INSERT [Order Details]
Trigger
[Order Details] VALUES
Code: VALUES
Trigger Code:
(10525, 2,
2, 19.00,
USE 5,
5, 0.2)
Northwind
11 INSERT
(10525, Statement
19.00,
USE
CREATE
Northwind to a Table with an INSERT
0.2)
CREATE TRIGGER OrdDet_Insert
TRIGGER OrdDet_Insert
Trigger Defined
ON [Order
Order
Details]
ON [Order Details]
Details
FOROrder
FOR INSERTDetails
INSERT
OrderID
ASOrderIDProductID
AS ProductIDUnitPrice
UnitPriceQuantity
QuantityDiscount
Discount
22 UPDATE P SET
INSERTUnitsInStock
Statement
UPDATE
10522
10522
P SET
10 Logged
10 =31.00 77 0.2
UnitsInStock =31.00
(P.UnitsInStock
(P.UnitsInStock 0.2 –– I.Quantity)
I.Quantity)
10523
FROM
10523
FROM 41
Products
41
Products 9.65
AS
9.65P 99
INNER
AS P INNER 0.15
JOIN
0.15
JOIN Inserted
Inserted AS
AS II
33 ON
ON P.ProductID
P.ProductID == I.ProductID
I.ProductID
Trigger 10524
Actions 7
10524 Executed
7 30.00 30.00 24 240.0 0.0
Order Details
Order Details 10523 2 19.00 5 0.2
Products
OrderID
OrderIDProductID
ProductIDUnitPrice
UnitPriceQuantity
QuantityDiscount
Discount Products
ProductID
ProductID UnitsInStock
UnitsInStock …… ……
10522
10522 10 10 31.00
31.00 77 0.2
0.2
10523 41 9.65 99 0.15 11 15
15
Insert
10523 statement
41 logged
9.65 0.15
10524 77 30.00 24 0.0 22 15
10
10
10524inserted
inserted 30.00 24 0.0
10523 2 19.00 5 0.2 33 65
65
10523
10523 22 19.00
19.00 55 0.2
0.2 44 20
20
How a DELETE Trigger Works
DELETE Statement to a table with a DELETE Trigger Defined
Trigger Actions Execute
Categories
Categories
11DELETE Statement
CategoryID to
CategoryID a Table withDescription
CategoryName
CategoryName a DELETEPicture
Description Picture
DELETE Categories
DELETE Statement 11
CategoriesDefined Beverages Products
Products
Soft drinks, coffees… 0x15…
Beverages Soft drinks, coffees… 0x15…
WHERE ProductID Discontinued … …
Condiments ProductID Discontinued
……0x15…

WHERE 22 Condiments Sweet
CategoryID
CategoryID == 44 Sweetand
and savory
savory… 0x15…
22 33 Confections 11
Confections Desserts,
Desserts, 00
candies,
candies,…… 0x15…
0x15…
DELETE Statement
4 Logged 22
Dairy Products Cheeses
2 1
00 0x15…
USE Northwind
USE Northwind
CREATE TRIGGER Category_Delete 33 00
33
CREATE TRIGGER Category_Delete
ON Trigger
ON CategoriesActions Executed
Categories 44 00
FOR
FOR DELETE
DELETE
AS
AS
UPDATE
UPDATE PP SET
SET Discontinued
Discontinued == 11
FROM
FROM Products
Products ASAS PP INNER
INNER JOIN
JOIN deleted
deleted AS
AS dd
ON P.CategoryID
ON DELETE == d.CategoryID
statement
P.CategoryID logged
d.CategoryID
Deleted
Deleted
44 Dairy
DairyProducts
Products Cheeses
Cheeses 0x15…
0x15…
How an UPDATE Trigger Works
TRIGGER Actions Execute
UPDATE Statement to a table with an UPDATE Trigger Defined
USE
USE Northwind
Northwind
GO UPDATE Employees
GO UPDATE Employees
CREATE TRIGGER Employee_Update
ON
ON
SET
CREATE
SET UPDATE
EmployeeID
11 EmployeeID
TRIGGER
Employees
Employees
=Statement
= 17
Employee_Update
17 to a Table with an UPDATE
WHERE EmployeeID
WHERE EmployeeID = 2 = 2
FOR
AS
FOR UPDATETrigger Defined
UPDATE
Employees
AS
AS Employees
IF
IF UPDATE
IF UPDATE (EmployeeID)
UPDATE (EmployeeID)
(EmployeeID) EmployeeID
BEGIN
BEGIN TRANSACTION
BEGIN TRANSACTION
TRANSACTION EmployeeID LastName
LastName FirstName
FirstName Title
Title HireDate
HireDate
22 UPDATE
RAISERROR
RAISERROR
RAISERROR Statement
('Transaction
('Transaction
('Transaction cannot
1
cannotLogged
cannot be
Davolio
be asNancy
INSERT
be processed.\
processed.\
processed.\ Sales and
Rep. ~~~
*****
***** Employee
***** Employee ID
Employee ID number
ID number
1cannot
number cannot
Davolio
cannot bebe Nancy
modified.',
be modified.',
Sales
modified.', 10, 10,Rep.1)
10, 1)1)
~~~
ROLLBACK
ROLLBACK
ROLLBACK DELETE Statements
TRANSACTION
TRANSACTION
TRANSACTION 22 Fuller
Barr
Barr Andrew
Andrew Vice
RR Pres. ~~~ ~~~
33 Leverling
Leverling Janet
Janet Sales
SalesRep.
Rep. ~~~
~~~
Transaction
3 cannot be processed. 44 Peacock
Peacock Margaret
MargaretSales
SalesRep.
Rep. ~~~
~~~
3 Trigger
***** Member Actions
number cannot Executed
be modified
***** Member number cannot be modified
Employees
UPDATE Statement loggedEmployees
as INSERT and DELETE Statements
EmployeeID
EmployeeID LastName
LastName FirstName
FirstName Title
Title HireDate
HireDate
inserted
inserted 11 Davolio
Davolio NancyNancy Sales
SalesRep.
Rep. ~~~
~~~
17
17 Fuller Andrew
Fuller 2 Andrew Vice Pres.
Vice Pres.
Fuller ~~~
Andrew~~~R Pres.
2 Barr
Barr Andrew Vice
R ~~~
~~~
deleted
deleted 33 Leverling
Leverling Janet
Janet Sales
SalesRep.
Rep. ~~~
~~~
22 Fuller 44Andrew
Fuller Peacock
Andrew Vice
VicePres.
Peacock Margaret
~~~Sales
~~~
Margaret
Pres. SalesRep.
Rep. ~~~
~~~
How INSTEAD OF Trigger Works
Create a View That Combines Two or More Tables
CREATE
CREATE VIEW
UPDATE is Made
VIEW
toCustomers
11 View
the
Customers AS
INSTEADAS OF Trigger Can Be on a Table or View
SELECT
SELECT **
FROM
FROM CustomersMex
CustomersMex Customers
INSTEAD
UNION OF
UNION Customers
SELECT ** CustomerID
CustomerIDCompanyName
CompanyName Country
Country Phone
Phone ……
trigger
SELECTdirects the
22 The Action
FROM
update to
FROM the base That
CustomersGer
CustomersGer Initiates
ALFKI
ALFKI
ALFKI theFu…
Alfreds
Alfreds Trigger
Fu… Germany
Germany Does NOT Occur
030-0074321
030-0074321 ~~~
~~~
table ANATR
ANATR Ana
AnaTrujill…
Trujill… Mexico
Mexico (5)
(5)555-4729
555-4729 ~~~
~~~
ANTON
ANTON Antonio
AntonioM…
M… Mexico
Mexico (5)
(5)555-3932
555-3932 ~~~
~~~
Original Insert to
33
the Allows Updates to Views Not Previously Updateable
Customers
CustomersMex
CustomersMex
View Does
CustomerID
CustomerID Not
CompanyName
CompanyName Country
Country
CustomersGerPhone
Phone ……
CustomersGer
Occur
ANATR Ana Trujill… Mexico (5) 555-4729
CustomerID CompanyName~~~
Country Phone …
ANATR Ana Trujill… Mexico (5) 555-4729
CustomerID CompanyName~~~ Country Phone …
ANTON
ANTON Antonio
AntonioM…
M… Mexico
Mexico (5) 555-3932 ~~~
Germany
ALFKI(5) 555-3932
ALFKI Alfreds Fu…~~~
AlfredsFu… Germany 030-0074321
030-0074321 ~~~
~~~
CENTC Centro Co… Mexico
CENTC Centro Co… Mexico (5) 555-3392 ~~~
BLAUS(5) 555-3392
BLAUS Blauer Se…~~~
BlauerSe… Germany
Germany 0621-08460
0621-08460 ~~~
~~~
DRACD
DRACD Drachenb…
Drachenb… Germany
Germany 0241-039123
0241-039123 ~~~
~~~
How Nested Triggers Work
Order_Details
Order_Details
OrDe_Update
OrDe_Update OrderID
OrderIDProductID
ProductIDUnitPrice
UnitPriceQuantity
QuantityDiscount
Discount
10522
10522 10
10 31.00
31.00 77 0.2
0.2
10523
10523 41
41 9.65
9.65 99 0.15
0.15
10524
10524 77 30.00
30.00 24
24 0.0
0.0
10525 2 19.00 5 0.2

Placing an order causes the


OrDe_Update trigger to
Products
Products execute
InStock_Update
InStock_Update ProductID
ProductID UnitsInStock
UnitsInStock …… ……
Executes an UPDATE
11 15
15 statement on the Products
2 15
10
10 table
33 65
65
44 20
20
InStock_Update trigger
executes
UnitsInStock + UnitsOnOrder Sends message
is < ReorderLevel for ProductID 2
Recursive Triggers
• Activating a Trigger Recursively
• Types of Recursive Triggers
– Direct recursion occurs when a trigger fires and performs an action that causes the same
trigger to fire again
– Indirect recursion occurs when a trigger fires and performs an action that causes a trigger
on another table to fire
• Determining Whether to Use Recursive Triggers
Examples of Triggers
• Enforcing Data Integrity
• Enforcing Business Rules
Enforcing Data Integrity
CREATE
CREATE TRIGGER
TRIGGER BackOrderList_Delete
BackOrderList_Delete
ON
ON Products FOR
Products FOR UPDATE
UPDATE
AS
AS
IF
IF (SELECT
(SELECT BO.ProductID
BO.ProductID FROM
FROM BackOrders
BackOrders ASAS BO
BO JOIN
JOIN
Inserted AS I ON BO.ProductID = I.Product_ID
Inserted AS I ON BO.ProductID = I.Product_ID
)) >> 00
BEGIN
BEGIN
DELETE
DELETE BO BO FROM
FROM BackOrders
BackOrders AS
AS BO
BO
INNER JOIN Inserted
INNER JOIN Inserted AS IAS I
ON
ON BO.ProductID
BO.ProductID == I.ProductID
I.ProductID
END
END

Products
Products BackOrders
BackOrders
ProductID
ProductID UnitsInStock
UnitsInStock …… …… ProductID
ProductID UnitsOnOrder
UnitsOnOrder ……
11 15
15 11 15
15
2 15
10 Updated
Updated 12 10
10 12 10
33 65
65 33 65
65
44 20 Trigger
TriggerDeletes
Deletes Row
Row 2 15
20
Enforcing Business Rules
Products with Outstanding Orders Cannot Be Deleted
IF
IF (Select
(Select Count
Count (*)
(*)
FROM
FROM [Order Details] INNER
[Order Details] INNER JOIN
JOIN deleted
deleted
ON [Order Details].ProductID = deleted.ProductID
ON [Order Details].ProductID = deleted.ProductID
)) >> 00
ROLLBACK
ROLLBACK TRANSACTION
TRANSACTION
DELETE statement executed on Trigger code Transaction
Product table checks the Order Details rolled back
table
Products
Products Order
OrderDetails
Details
ProductID
ProductID UnitsInStock
UnitsInStock …… …… OrderID
OrderIDProductID
ProductIDUnitPrice
UnitPriceQuantity
QuantityDiscount
Discount
11 1515 10522
10522 10
10 31.00
31.00 77 0.2
0.2
22 010
10 10523
10523 22 19.00
19.00 99 0.15
0.15
33 6565 10524
10524 41
41 9.65
9.65 24
24 0.0
0.0
44 2020 10525
10525 77 30.00
30.00

'Transaction
'Transaction cannot
cannot bebe processed'
processed'
'This
'This product
product has
has order
order history'
history'
Performance Considerations
• Triggers Work Quickly Because the Inserted and
Deleted Tables Are in Cache
• Execution Time Is Determined by:
– Number of tables that are referenced
– Number of rows that are affected

• Actions Contained in Triggers Implicitly Are Part of


a Transaction
T-SQL Enhancements
• Common Table expression
• Try Catch
• PIVOT and UNPIVOT
• TOP
• And many other enhancements
Exercises.. Contd
1. What is a table variable and where does it get stored? How is it different from
Temporary table?
2. Create a table and write insert, update and delete triggers on the table which will
display a custom error message to the user.
Exercises.. Contd
3. Consider the given scenario below and
provide the solution
Assume that there are two tables as
mentioned below

CREATE TABLE Person CREATE TABLE EmployeeTable


( (
SSN char(11) PRIMARY KEY, EmployeeID int PRIMARY KEY,
Name nvarchar(100), SSN char(11) UNIQUE,
Address nvarchar(100), Department nvarchar(10),
Birthdate datetime Salary money,
) CONSTRAINT FKEmpPer FOREIGN KEY
(SSN)
REFERENCES Person (SSN)
)

Contd….
Exercises.. Contd
Now create a view Employee as mentioned below

CREATE VIEW Employee AS


SELECT P.SSN as SSN, Name, Address, Birthdate, EmployeeID, Department, Salary
FROM Person P, EmployeeTable E
WHERE P.SSN = E.SSN

Create another table PersonDuplicates as mentioned below which will be used to log the
duplicate records.

CREATE TABLE PersonDuplicates


(
SSN char(11),
Name nvarchar(100),
Address nvarchar(100),
Birthdate datetime,
InsertSNAME nchar(100),
WhenInserted datetime
) Contd….
Exercises.. Contd
Now create a instead of trigger which takes care of below mentioned logic when a user tries
to insert a record.
Check for duplicate Person. If there is no duplicate, then do an insert in the person table else
log an attempt to insert duplicate Person row in PersonDuplicates table.
Also check for duplicate Employee. If there is no duplicate, do an INSERT else update the
employeetable record with the new inserted value.
Exercises.. Contd
• What is CTE, How is it different from View? Give an example of CTE
• Write a TSQL statement to Delete top 10 records from a table without using rowcount
• Find the difference between the below two insert statements
INSERT TOP (10) top10sales
SELECT salesOrderId, totalDue
FROM sales.salesOrderHeader
ORDER BY totalDue desc

INSERT top10sales
SELECT TOP (10) salesOrderId, totalDue
FROM sales.salesOrderHeader
ORDER BY totalDue desc
References
URL :
http://msdn2.microsoft.com/en-us/library/ms188927.aspx
http://msdn2.microsoft.com/en-us/library/ms191524.aspx
Answers

Solutions to the
Exercise Questions
Thank You

You might also like