Sqldev320a Week6-2
Sqldev320a Week6-2
TRIGGERS
CURSORS
• WHAT ARE CURSORS
• SYSTEM CURSOR FUNCTIONS
• COMMON CURSOR ARGUMENTS
Error Error Handling
Handling
Functions
Accessing the @@ERROR object
Creating customer errors with
RAISERROR()
Capturing error info with TRY…
CATCH…
THROW…
Error Object: @@ERROR
IF NOT EXISTS(
SELECT LoginID
FROM HumanResources.Employee
WHERE BusinessEntityID = 0)
THROW 76543, '[SQLDEV320A] Employee not
found.', 1;
RAISERROR THROW statement
Differences statement
Trigger Types
• FOR | AFTER trigger
Database
• INSTEAD OF trigger
DMLTriggers
Triggers INSERT, UPDATE or DELETE statement to a table or
view
DDL Triggers
CREATE, ALTER, DROP, GRANT DENY, REVOKE,
UPDATE
What are
triggers
•A trigger is a special
kind of stored
procedure that
automatically
executes when a
table event occurs in
the database server.
Enforce Enforce business logic
•DMLtrigger
-- 1 Create table
object
CREATE TABLE Table1
(SRC_ID int IDENTITY,
[Description]
NVARCHAR(100));
GO
-- 2 Create Insert
trigger
CREATE TRIGGER
i_trgTable1
ON Table1
FOR INSERT AS
PRINT
GETDATE();
GO
AFTER Trigger Example:
USE
[AdventureWorks2019]
GO
CREATE TRIGGER
trg_OrderDetailNotDisc
AS
ontinued
-- Prevent
ON [Sales]. for discontinued
orders IF items AFTER
[SalesOrderDetail]
EXISTS (
INSERT, UPDATE
SELECT 1
FROM Production.Product p
JOIN
INSERTED
ON i
i.productid = p.productid
WHERE p.DiscontinuedDate < GETDATE()
)
BEGI
N
R
A
I
INSERTED • Inserted and Deleted virtual tables are
and created for the trigger
• Each trigger has its own Inserted and
DELETED Deleted tables
• For every new set of values in a row,
virtual there's a row in the
tables • Inserted virtual table
• For every old set of values in a row,
there's a row in the Deleted virtual
table
• An update generates an Inserted and
Deleted row for every single update.
More on virt
ual tables
Using INSERTED and DELETED virtual
tables
USE
[test]
GO
IF
OBJECT_ID
('[dbo].
[Table2]'
, 'U') IS
NOT NULL
--DROP
Create Insert trigger
TABLE TRIGGER
CREATE ON
[dbo].T FOR UPDATE, Table2
u_trgTest
able2 DELETE AS
INSERT,
GO SELECT 'inserted', * FROM INSERTED -- Virtual table containing
INSERTED rows
SELECT
CREATE 'deleted',*
TABLE FROM
Table2(Col1 intDELETED--
IDENTITY,Virtual table containing DELETED
Col2 varchar(100),
Col3rows
int) GO
GO
-- Test trigger
INSERT INTO Table2 VALUES ('Inserted value',
1); UPDATE Table2 SET Col2 = 'Updated
value'; DELETE FROM Table2 WHERE Col1 = 1;
Using DDL triggers:
Triggered by:
CREATE
ALTER
DROP
DDLTrigger:
Logon Trigger:
1
Writing
• What are Cursors
• Examples
Cursors •
•
Discussions
Pros and Cons
What is a cursor?
A 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.
Cursor Syntax
DECLARE cursor_name
CURSOR [LOCAL | GLOBAL] [FORWARD_ONLY | SCROLL]
[STATIC | KEYSET | DYNAMIC | FAST_FORWARD]
[READ_ONLY | SCROLL_LOCKS | OPTIMISTIC]
[TYPE_WARNING]
FOR select_statement
[FOR UPDATE [OF column_name [,...n]]]
Steps to use a Cursor:
--Declare the cursor and associate it with a query
DECLARE <cursorname> CURSOR FOR <query>
--Loop until the end of the cursor is reached WHILE @@FETCH_STATUS = 0 BEGIN
<SQL statements>
--Release resources
DEALLOCATE <cursorname>;
• @@FETCH_STATUS
• 0 Successful
• -1 Failed
• -2 Row missing
System • @@CURSOR_ROWS
• -m The number of rows in the
Cursor keyset
• -1 Dynamic cursor
Functions:
• 0 No cursor has been
opened
• n Total number of rows
in the cursor
•3) CURSOR_STATUS
• 'local' | 'global' | 'variable'
Common Cursor Arguments
Argument Purpose
UPDATE [OF column_name] for update columns within the cursor
FORWARD_ONLY Cursor can only be scrolled from first to the last row
OPEN CustList;
WHILE @@FETCH_STATUS = 0
BEGIN
IF (SELECT COUNT(CustomerID) FROM Sales.Customer) > 0
SELECT AccountNumber FROM Sales.Customer
WHERE CustomerID = @customerid;
PRINT @customerid;
CLOSE CustList;
DEALLOCATE CustList; -- Required to DEALLOCATE
GO
What does this code do?
DECLARE @SPID int
OPEN c_idleSessions
FETCH NEXT FROM c_idleSessions INTO @SPID;
WHILE @@FETCH_STATUS = 0
BEGIN
PRINT 'killing process: ' + CAST(@spid as NVARCHAR(5)) EXEC('kill ' + @spid)
FETCH NEXT FROM c_idleSessions INTO @spid
END
CLOSE c_idleSessions;
DEALLOCATE c_idleSessions;
GO
It depends on:
Size of the result set.
Percentage of the data likely tobe needed.
Performance of the cursor open.
Need for cursor operations, such as scrolling or
positioned updates.
Level of visibility to data modifications made by other
Choosing a users.
Simple rules:
Cursor Type Use default settings when possible.
Dynamic cursors open faster than static or keyset-driven
cursors.
In joins, keyset-driven and static cursors can be faster
than dynamic cursors.
Keyset-driven or static cursors must be used if you want
to do absolute fetches.
Keyset-driven or static cursors increase the usage of
tempdb.
Cursor Pros and Cons
Pros
They are necessary for some dynamic operations that can't be accomplished with set-based
operations.
They are simple to understand, which makes them ideal for quick-and-dirty programming
A tool of choice for beginner SQL developers or developers who are used to procedural
programming
They outperform while loops when you need row-by-row processing.
They are ideal for scrolling a portion of a large resultsset.
By default, they provide a window into your tables or results set, which maximizes concurrency
Confor
s all applications.
They are procedural iterative functions that are not like database set operations
They are resource intensive and generally slower than other application approaches
They may not scale to support processing and better options are available
They may lock table inserts or updates causing excessiveblocking
There are better alternatives for FOREACH operations
Week 6 Assignment