Lect 4

Download as pdf or txt
Download as pdf or txt
You are on page 1of 32

Lebanese French University

College of Engineering and Computer Science


Department of Information technology
First Semester
2023 – 2024

Asst. Lect. Mateen Naser Ridha


[email protected]

Advanced Database II
Lecture 4
Procedures

Triggers

Advanced Database II| IT & CE| Stage #3 4/14/2024 2


Stored Procedure

Advanced Database II| IT & CE| Stage #3 4/14/2024 3


Architecture Elements
▪ A full-fledged systems production and operation environment will
consist of a multitude of elements
▪ Databases
▪ Tables, relationships, indices
▪ Stored procedures
▪ Database connectivity
▪ System connectivity (DSN, ADO.Net)
▪ Application connectivity
▪ Applications

Advanced Database II| IT & CE| Stage #3 4/14/2024 4


Procedures
▪ Stored Procedure (SP) is a group of one or more pre-compiled SQL
statements into a logical unit.

▪ SP can be called accessed by other SP or by


external applications

▪ Simplest SP execute a single SQL statement

▪ SP can be incredibly complex

▪ SP can return results


▪ Individual discrete values
▪ Entire recordsets (query results)

Advanced Database II| IT & CE| Stage #3 4/14/2024 5


Procedures

DATABASE COMPONENTS DATABASE APPLICATIONS


CONNECTIVITY
TABLES & STORED
(ADO.Net)
RELATIONSHIPS PROCEDURES

A stored procedure is a program that is stored within the database and is


compiled when used

Advanced Database II| IT & CE| Stage #3 4/14/2024 6


Procedures
▪ A stored procedure is a prepared SQL code that you can save, so the
code can be reused over and over again. So if you have an SQL query
that you write over and over again, save it as a stored procedure, and
then just call it to execute it.

▪ Stored procedures can receive input parameters and they can return
results
▪ Stored procedures can be called from:
▪ Programs written in standard languages, e.g., Java, C#
▪ Scripting languages, e.g., JavaScript, VBScript
▪ SQL command prompt, e.g., SQL*Plus, Query Analyzer

Advanced Database II| IT & CE| Stage #3 4/14/2024 7


Stored Procedure Advantages
▪ Greater security as store procedures are always stored on the
database server
▪ SQL can be optimized by the DBMS compiler
▪ Code sharing resulting in:
▪ Less work
▪ Standardized processing
▪ Specialization among developers

Advanced Database II| IT & CE| Stage #3 4/14/2024 8


Script to Create a Simple Stored Procedure

CREATE PROCEDURE [schema_name].procedure_name


@parameter_name data_type,
....
parameter_name data_type
AS
BEGIN
-- SQL statements
-- SELECT, INSERT, UPDATE, or DELETE statement
END

Advanced Database II| IT & CE| Stage #3 4/14/2024 9


Procedures

▪ Create a procedure to find the ID and the name of all the


Instructors, then call that procedure to show the results.

create proc spInst_info


As
Begin
select ID, Name from instructor
End

Call Stored Procedure Execute spInst_info

Advanced Database II| IT & CE| Stage #3 4/14/2024 10


Procedures
▪ Define a Procedure that, given the name of a student, returns the
Information about that student.

▪ Then call that procedure to show the results.

create procedure SP_info2


(@Std_name nvarchar(20))
as
Begin
select ID, name, gender from students2 where name = (@Std_name
End

Call Stored Procedure SP_info2 'Jain'

Advanced Database II| IT & CE| Stage #3 4/14/2024 11


Procedures
▪ To create an output parameter for a stored procedure, you use the following syntax:

Parameter name data type OUTPUT

▪ A stored procedure can have many output parameters.

▪ In addition, the output parameters can be in any valid data type e.g., integer, date,
and varying character.

Advanced Database II| IT & CE| Stage #3 4/14/2024 12


Procedures
▪ The following stored procedure finds products by model year and returns the
number of products via the @product_count output parameter:

First, we created an output parameter named @product_count to store the


number of products found:

Second, after the SELECT statement, we assigned the number of rows returned by
the query (@@ROWCOUNT) to the @product_count parameter.

Note: that the @@ROWCOUNT is a system variable that returns the number of rows
read by the previous statement.

Advanced Database II| IT & CE| Stage #3 4/14/2024 13


Calling stored procedures with
output parameters
To call a stored procedure with output parameters, you follow these steps:

✓ First, declare variables to hold the values returned by the output parameters
Variable to hold the value of the output
✓ Second, use these variables in the stored procedure call. parameter of the stored procedure

For example, the statement that located on the

side, executes the uspFindProductByModel

stored procedure

passing the
can call the uspFindProductByModel parameters
stored procedure as follows:
show the value of the @count variable

Advanced Database II| IT & CE| Stage #3 4/14/2024 14


Trigger

Advanced Database II| IT & CE| Stage #3 4/14/2024 15


Trigger

▪ Triggers are special types of Stored Procedures that are ran automatically by the
database whenever a certain modification (event) occurs.
▪ The modification statements may include
INSERT, UPDATE, and DELETE.
▪ User cannot fire the trigger explicitly , it gets fired implicitly on the basis of certain
specified event
▪ Trigger stored program that is executed by the DBMS whenever a specified event
occurs
▪ Not a stand alone object

Advanced Database II| IT & CE| Stage #3 4/14/2024 16


Types of SQL Triggers
SQL Server provides three type of triggers:

▪ Data manipulation language (DML) triggers which are invoked automatically in response to
INSERT, UPDATE, and DELETE events against tables.

▪ Data definition language (DDL) triggers which fire in response to CREATE, ALTER, and
DROP statements. DDL triggers also called to some system stored procedures that perform
DDL-like operations.

▪ Logon triggers which fire in response to LOGON events

Advanced Database II| IT & CE| Stage #3 4/14/2024 17


Create DML Triggers

▪ The CREATE TRIGGER statement allows you to create a new trigger that is running automatically
whenever an event such as INSERT, DELETE, or UPDATE occurs against a table.

▪ The following illustrates the syntax of the CREATE TRIGGER statement:


The schema_name is the name of the
schema to which the new trigger
belongs. The schema name is optional.

The table_name is the


table to which the trigger
applies.

The NOT FOR REPLICATION option instructs


SQL Server not to fire the trigger when data
modification is made as part of a replication A single trigger can fire in response to
process. one or more actions against the table.

is one or more Transact-SQL used to carry


out actions once an event occurs.

Advanced Database II| IT & CE| Stage #3 4/14/2024 18


Create DML Triggers
Now, we created a trigger that stores transaction records of each
insert operation on the table1(students) into the table2 (students 2 ). select * from students2;

CREATE TRIGGER new_hire


ON students
FOR INSERT
AS
BEGIN
insert INTO students2 values(11, 'Kim Hans','M')
END select * from students;

Testing the trigger

After creating a trigger, we will try to add the following record into
the table1:
INSERT INTO students VALUES (6,'Peter', 'Male');

Advanced Database II| IT & CE| Stage #3 4/14/2024 19


DDL Triggers
▪ SQL Server DDL triggers respond to server or database events rather than to table
data modifications.

▪ These events created by the SQL statement that normally starts with one of the following
keywords CREATE, ALTER, DROP, GRANT, DENY, REVOKE, or UPDATE
STATISTICS.

▪ For example, we can write a DDL trigger to log whenever a user issues a CREATE
TABLE or ALTER TABLE statement.

Advanced Database II| IT & CE| Stage #3 4/14/2024 20


DDL Triggers
▪ The following shows the syntax of creating a DDL trigger:

Use DATABASE if the trigger


respond to database-scoped CREATE TRIGGER trigger_name
events
ON { DATABASE | ALL SERVER}
Use ALL SERVER if the
[WITH ddl_trigger_option] trigger responds to the
specifies ENCRYPTION and / server-scoped events.
or EXECUTE AS clause
FOR {event_type | event_group }
AS {sql_statement}

• ENCRYPTION encrypts the Indicates a DDL event that causes the The event_group is a group
definition of the trigger. trigger to fire e.g., CREATE_TABLE, of event_type event such as
ALTER_TABLE DDL_TABLE_EVENTS.
• EXECUTE AS defines the
security context under which the
trigger is executed.

Advanced Database II| IT & CE| Stage #3 4/14/2024 21


Create DDL Triggers
Example:

In the following example, DDL trigger safety will fire whenever a DROP_TABLE or ALTER_TABLE
event occurs in the database.

CREATE TRIGGER safety


ON DATABASE
FOR DROP_TABLE, ALTER_TABLE
AS
PRINT 'You must disable Trigger "safety" to drop or alter tables!'
ROLLBACK;

Advanced Database II| IT & CE| Stage #3 4/14/2024 22


Create DDL Triggers
Example:

In the following example, a DDL trigger prints a message if any CREATE_DATABASE event occurs
on the current server instance.

CREATE TRIGGER ddl_trig_database


ON ALL SERVER
FOR CREATE_DATABASE
AS
PRINT 'Database Created.'
SELECT
EVENTDATA().value('(/EVENT_INSTANCE/TSQLCommand/CommandText)[1]','nvarchar(max)')
GO

Advanced Database II| IT & CE| Stage #3 4/14/2024 23


Logon Triggers

▪ Logon triggers fire stored procedures in response to a LOGON event.

▪ This event is raised when a user session is established with an instance of SQL
Server.

▪ Logon triggers fire after the authentication phase of logging in finishes, but before the
user session is actually established.

▪ As a result, the SQL Server error log will display all messages created by the trigger,
including error messages and the PRINT statement messages.

▪ If authentication fails, logon triggers do not execute.

Advanced Database II| IT & CE| Stage #3 4/14/2024 24


Logon Triggers

A LOGON trigger can be used in controlling server sessions by


- tracking login activity,
- restricting logins to the SQL Server, or
- limiting the number of sessions for a particular login.

Advanced Database II| IT & CE| Stage #3 4/14/2024 25


Logon Triggers
For example:
USE master;
in the following code, the GO
CREATE LOGIN login_test WITH PASSWORD = N'3KHJ6dhx(0xVYsdf' MUST_CHANGE,
logon trigger denies log in CHECK_EXPIRATION = ON;
GO
attempts to SQL Server GRANT VIEW SERVER STATE TO login_test;
initiated by login login_test if GO
CREATE TRIGGER connection_limit_trigger
there are already three user ON ALL SERVER WITH EXECUTE AS N'login_test'
FOR LOGON
sessions created by that login. AS
BEGIN
IF ORIGINAL_LOGIN()= N'login_test' AND
(SELECT COUNT(*) FROM sys.dm_exec_sessions
WHERE is_user_process = 1 AND
original_login_name = N'login_test') > 3
ROLLBACK;
END;

Advanced Database II| IT & CE| Stage #3 4/14/2024 26


Logon Triggers
For example: The following LOGON trigger restricts the login attempt to SQL Server by sa login
if there are already two user sessions created by that login.

CREATE TRIGGER trgLoginConnection


ON ALL SERVER WITH EXECUTE AS N'sa'
FOR LOGON
AS
BEGIN
IF ORIGINAL_LOGIN() = N'sa' AND
(SELECT COUNT(*) FROM sys.dm_exec_sessions
WHERE is_user_process = 1 AND
original_login_name = N'sa') > 2
ROLLBACK;
END;

Advanced Database II| IT & CE| Stage #3 4/14/2024 27


Difference between Stored Procedure, SQL
Function, and Trigger

Advanced Database II| IT & CE| Stage #3 4/14/2024 28


Difference between Stored Procedure, SQL
Function, and Trigger

Advanced Database II| IT & CE| Stage #3 4/14/2024 29


Difference between Stored Procedure, SQL
Function, and Trigger

Advanced Database II| IT & CE| Stage #3 4/14/2024 30


Difference between Stored Procedure, SQL
Function, and Trigger

Advanced Database II| IT & CE| Stage #3 4/14/2024 31


Thanks
Any Question

Advanced Database II| IT & CE| Stage #3


?
4/14/2024 32

You might also like