0% found this document useful (0 votes)
30 views

Stored Procedures and Triggers

The document discusses database programming concepts like stored procedures, functions, and triggers. It covers how to declare and assign variables, use control flow tools like IF/ELSE statements and WHILE loops, and print messages. It also explains what stored procedures are, how they differ from SQL statements, and how to create, update, and delete procedures. Procedures allow grouping SQL statements and optional parameters to be compiled and executed as a single unit for improved performance.

Uploaded by

The Real Stuff
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
30 views

Stored Procedures and Triggers

The document discusses database programming concepts like stored procedures, functions, and triggers. It covers how to declare and assign variables, use control flow tools like IF/ELSE statements and WHILE loops, and print messages. It also explains what stored procedures are, how they differ from SQL statements, and how to create, update, and delete procedures. Procedures allow grouping SQL statements and optional parameters to be compiled and executed as a single unit for improved performance.

Uploaded by

The Real Stuff
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

Objectives

1. Database Programming
2. Stored Procedure
3. Function
4. Trigger

Stored Procedures and Triggers

Pearson Education © 2014 Pearson Education © 2014

1. Database Programming 1.1 Variables


1.1 Variables Declare a variable:
DECLARE @limit money
1.2 Control-of-Flow Tools DECLARE @min_range int, @hi_range int
Assign a value into a variable:
SET @min_range = 0, @hi_range = 100

SET @limit = $10

Assign a value into a variable in SQL statement:


SELECT @price = price FROM titles
WHERE title_id = 'PC2091'

Pearson Education © 2014 Pearson Education © 2014

1.2 Control-of-Flow Tools 1.2.1 BEGIN…END


1.2.1 BEGIN…END Defines a statement block
1.2.2 IF…ELSE Other Programming Languages:
1.2.3 CASE … WHEN C#, Java, C: { … }
1.2.4 RETURN [n] Pascal, Delphi: BEGIN … END
1.2.5 WHILE
1.2.6 PRINT

Pearson Education © 2014 Pearson Education © 2014


1.2.2 IF…ELSE 1.2.3 CASE … WHEN
CASE input_expression
Defines conditional and, optionally, alternate WHEN when_expression THEN result_expressi
execution when a condition is false on
IF Boolean_expression [WHEN when_expression THEN
T-SQL_statement | block_of_statements result_expression…n]
[ELSE [ELSE else_result_expression ]
T-SQL_statement | block_of_statements ]
Example: END
Example:
IF (SELECT ytd_sales FROM titles WHERE title_id = 'PC1035') > 5000 SELECT CASE payterms
PRINT 'Year-to-date sales are greater than $5,000 for PC1035.‘ WHEN 'Net 30' THEN 'Payable 30 days after invoice'
WHEN 'Net 60' THEN 'Payable 60 days after invoice'
WHEN 'On invoice' THEN 'Payable upon receipt of invoice'
ELSE 'None'
END as Payment_Terms FROM sales ORDER BY payterms
Other Programming Language
Pearson Education © 2014
C#, Java: Switch … Case ; VB: Select … Case
Pearson Education © 2014

1.2.4 RETURN [n] 1.2.5 WHILE


Repeats a statement (or block) while a specific
Exits unconditionally of Trigger, Procedure or condition is true
Function and return a value (if any). WHILE Boolean_expression
SQL_statement | block_of_statements
[BREAK] SQL_statement | block_of_stateme
nts [CONTINUE]
Example:
WHILE (SELECT AVG(royalty) FROM roysched) < 25
BEGIN
UPDATE roysched SET royalty = royalty * 1.05
IF (SELECT MAX(royalty)FROM roysched) > 27 BREAK
ELSE CONTINUE
END
SELECT MAX(royalty) AS "MAX royalty"
FROM roysched
Pearson Education © 2014 Pearson Education © 2014

1.2.6 PRINT 2. Stored Procedure


Display message in SQL Query Analyze (Console) 2.1 What Is a Stored Procedure?
PRINT string 2.2 Stored Procedure vs. SQL Statement
Other Programming Languages: 2.3 Create, update and delete a procedure
Java: System.out.print
C#, VB.NET: Console.WriteLine

Pearson Education © 2014 Pearson Education © 2014


2.1 What Is a Stored Procedure?
2.2 Stored Procedure vs. SQL Statement
A stored procedure is a collection of SQL SQL Statement Stored Procedure
statements that SQL Server compiles into a Creating
single execution plan. - Check syntax
- Compile
First Time
Procedure is stored in cache area of memory - Check syntax
when the stored procedure is first executed so - Compile First Time
that it can be used repeatedly. SQL Server does - Execute - Execute
- Return data - Return data
not have to recompile it every time the stored
procedure is run. Second Time
Second Time
- Check syntax
It can accept input parameters, return output - Compile
- Execute
values as parameters, or return success or - Execute
- Return data

failure status messages. - Return data

Pearson Education © 2014 Pearson Education © 2014

2.3 Create, update and delete a 2.3.1 Create a Procedure


procedure
2.3.1.1 Syntax
2.3.1 Create a Procedure
2.3.1.2 Example 1 (Without parameters)
2.3.2 Update a Procedure
2.3.1.3 Example 2 (With parameters)
2.3.3 Delete a Procedure
2.3.1.4 Example 3 (Using RETURN)

Pearson Education © 2014 Pearson Education © 2014

2.3.1.1 Syntax 2.3.1.2 Example 1 (Without


parameters)
CREATE PROC[EDURE] procedure_name CREATE PROC Departments_Members
[ @parameter_name data_type] [= default] AS
OUTPUT][,...,n] SELECT Dep_Name, COUNT(Emp_ID) NumberOfMember
FROM Departments D, Employees E
AS WHERE D.Dep_ID = E.Dep_ID
SQL_statement(s) GROUP BY Dep_Name
Run Procedure
Execute Departments_Members

Pearson Education © 2014 Pearson Education © 2014


2.3.1.3 Example 2 (With 2.3.1.4 Example 3 (Using RETURN )
parameters) CREATE PROC GROUPLEADER_MEMBERS
CREATE PROC Department_Members @DeptName varchar(50) @Emp_Code varchar(10) = null
AS AS
SELECT Dep_Name, COUNT(Emp_ID) NumberOfMember IF @Emp_Code is null
FROM Departments D, Employees E BEGIN
WHERE D.Dep_ID = E.Dep_ID and Dep_Name = @DeptName PRINT 'Please enter Employee Code!'
GROUP BY Dep_Name RETURN
Run Procedure END
SELECT * FROM Employees
Execute Department_Members ‘Accounting’ WHERE EMP_EMP_ID = (SELECT EMP_ID FROM Employees
WHERE Emp_Code = @Emp_Code)
ORDER BY Emp_Name

Pearson Education © 2014 Pearson Education © 2014

2.3.2 Update a Procedure 2.3.3 Delete a Procedure


ALTER PROC[EDURE] procedure_name DROP PROCEDURE procedure_name
[ @parameter_name data_type]
[= default] [OUTPUT]
[,...,n]
AS
sql_statement(s)

Pearson Education © 2014 Pearson Education © 2014

3. Function 3.1 What is a Function?


3.1 What is a Function? See “What Is a Stored Procedure?” on slide 13
3.2 Scalar functions Example SQL Server supports three types of user-defined
3.3 Inline Table-valued Functions Example functions:
3.4 Multi-statement Table-Valued Functions Scalar functions
Example Inline table-valued functions
Multi-statement table-valued functions

Pearson Education © 2014 Pearson Education © 2014


3.2 Scalar functions Example
3.3 Inline Table-valued Functions
CREATE FUNCTION Revenue_Day (@Date datetime) Returns money
AS
Example
BEGIN CREATE FUNCTION AveragePricebyItems (@price money = 0.0) RETURNS table
DECLARE @total money AS
SELECT @total = sum(sali_Quantity * sali_price) RETURN ( SELECT Ite_Description, Ite_Price
FROM Sales_Orders s, Sales_Orders_Items si FROM Items
WHERE s.sal_number = si.sal_number and year(sal_date) = year(@Date) WHERE Ite_Price > @price)
and month(sal_date) = month(@Date) and day(sal_date)= day(@Date)
Use:
RETURN @total
END select * from AveragePricebyItems (15.00)

Use:
select dbo.Revenue_In_Day(GETDATE())
Pearson Education © 2014 Pearson Education © 2014

3.4 Multi-statement Table-Valued Functions 4. Trigger


Example
CREATE FUNCTION AveragePricebyItems2 (@price money = 0.0) RETURNS 4.1 What is a Trigger?
@table table (Description varchar(50) null, Price money null) AS
begin 4.2 Creating Syntax
insert @table SELECT Ite_Description, Ite_Price
FROM Items
4.3 Disable/Enable syntax
WHERE Ite_Price > @price 4.4 Deleted and Inserted tables
return
end 4.5 Example
Use: 4.6 Other Functions
select * from AveragePricebyItems2 (15.00)

Pearson Education © 2014 Pearson Education © 2014

4.1 What is a Trigger? 4.2 Advantages of Triggers


A trigger is a special type of stored procedure that is
executed automatically as part of a data modification.
Elimination of redundant code
A trigger is created on a table and associated with one Simplifying modifications
or more actions linked with a data modification Increased security
(INSERT, UPDATE, or DELETE). Improved integrity
When one of the actions for which the trigger is
defined occurs, the trigger fires automatically Improved processing power
Following are some examples of trigger uses: Good fit with client-server architecture
Maintenance of duplicate and derived data
Complex column constraints
Cascading referential integrity
Complex defaults
Inter-database referential integrity
Pearson Education © 2014 Pearson Education © 2014 30
4.3 Disadvantages of Triggers 4.4 Creating Syntax
Performance overhead
CREATE TRIGGER trigger_name
Cascading effects
ON <tablename>
Cannot be scheduled
<{FOR | AFTER}>
Less portable
{[DELETE] [,] [INSERT] [,] [UPDATE]}
AS
SQL_Statement [...n]

Pearson Education © 2014 31 Pearson Education © 2014

4.5 Disable/Enable syntax 4.6 Deleted and Inserted tables


When you create a trigger, you have access to two temporary tables
Disable syntax (the deleted and inserted tables). They are referred to as tables, but
they are different from true database tables. They are stored in
Disable trigger <trigger_name> on memory—not on disk.
<table_name> When the insert, update or delete statement is executed. All data will
be copied into these tables with the same structure.

Insert Update Delete


Enable syntax
new new old old
Enable trigger <trigger_name> on
<table_name> Inserted Deleted
Table Table
The values in the inserted and deleted tables are accessible only
within the trigger. Once the trigger is completed, these tables are no
longer accessible.
Pearson Education © 2014 Pearson Education © 2014

4.7 Example 4.8 Other Functions


CREATE TRIGGER Print_Update View contents of trigger
ON Bicycle_Inventory sp_helptext <trigger name>
FOR UPDATE View number of triggers of a table
AS sp_helptrigger <table name>
PRINT "The Bicycle_Inventory table was
updated"

Pearson Education © 2014 Pearson Education © 2014

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy