SlideShare uma empresa Scribd logo
1 de 24
T-SQL
(Transact-SQL)
T-SQL
T-SQL (Transact-SQL) is a set of
programming extensions from Sybase
and Microsoft that add several
features to the Structured Query
Language (SQL), including transaction
control, exception and error handling,
row processing and declared
variables.
T-SQL (Transact-SQL) is an extension of SQL
language.
1. Stored Procedure
"A stored procedure is a set of Structured
Query Language (SQL) statements with an
assigned name, which are stored in
a relational database management system as
a group, so it can be reused and shared by
multiple programs.”
A stored procedure is simply a compiled database object that
contains one or more T-SQL statements.
T-SQL Statement Examples
SQL Statements vs Stored Procedure
First Time
- Check syntax
- Compile
- Execute
- Return data
Second Time
- Check syntax
- Compile
- Execute
- Return data
Creating
- Check syntax
- Compile
First Time
- Execute
- Return data
Second Time
- Execute
- Return data
Create Stored Procedure
CREATE PROC[EDURE] procedure_name
[ @parameter_name data_type] [= default]
[OUTPUT]
[,...,n]
AS
T-SQL_statement(s)
Example 1 (Without Parameters)
Create procedure sp_customerList
AS
BEGIN
SELECT
customer_id,
customer_name,
customer_address
FROM
tbl_customer
ORDER BY
customer_name ASC
END
Example 2 (With Parameters)
IF (object_id (‘InsertCustomer’)) is NOT NULL
DROP PROCEDURE InsertCustomer
GO
CREATE PROCEDURE InsertCustomer
@FisrtName varchar(15),
@LastName varchar(15),
@Address varchar(50)
AS
--Sectionn 1: Define and initialize the local variable.
DECLARE @count int
SELECT @count = 0
--Section 2: Determine whether the record already exists
SELECT @count = COUNT(*)
FROM tbl_customer
WHERE FirstName = @FirstName
AND LastName = @LastName
--Section 3: Insert the record if it doesn’t exists
IF (@count = 0)
BEGIN
INSER INTO tbl_customer VALUES
(@FirsstNmae, @LastName, @Address)
PRINT ‘Customer record inserted’
END
ELSE
PRINT ‘Customer record already exists…’
GO
How to Execute Stored Procedures
EXEC InsertCustomer
@FirstName = ‘abc’,
@LastName = ‘xyz’,
@Address = ‘Pakistan’
Alter Stored Procedure
ALTER PROC[EDURE] procedure_name
[ @parameter_name data_type]
[= default] [OUTPUT]
[,...,n]
AS
t-sql_statement(s)
Delete Stored Procedure
DROP PROCEDURE procedure_name
Stored Procedure Offers Many Advantages
• You can avoid having to store all your T-SQL code in files. Stored
procedures are stored in the database itself, so you never have to
search through files to find the code you want to use.
• Stored procedure allows Faster Execution.
• If you have a report that needs to be run frequently, you can create
a stored procedure that produces the report. Anyone who has
access to the database and permission to execute the stored
procedure will be able to produce the report at will.
• Stored Procedure provide better Security to your data.
• Stored procedure reduces network traffic.
TRIGGERS
2. Trigger?
◦ Triggers are stored programs, which are
automatically executed or fired when some
events occur.
◦ We can define a Trigger as "A Trigger is a
Database object just like a stored procedure
or we can say it is a special kind of Stored
Procedure which fires when an event occurs
in a database.”
◦ User cannot fire the trigger explicitly, it gets
fired implicitly on the basis of certain specified
event.
Example of Trigger:
◦ If you write a letter to your friend and
then drop it in a mailbox without putting
enough postage on the envelope, you
trigger the post office to return the
letter to you along with a friendly
reminder that you need to add
postage. This reminder is triggered by
the lack of a stamp; otherwise, the
letter would have gone through the
mail without any delays.
Types of Triggers:
◦ Generally there are three types of
triggers available in sequel sever.
i. DML(Data Manipulating Language)
ii. DDL(Data Definition Language)
iii. Logon Triggers
DML:
◦ DML triggers run when insert, update or
delete statements modify data in the specified
table or view.
i. Insert : triggers are invoked by insert
statement
ii. Update: triggers are invoked by update
statement
iii. Delete : triggers are invoked by delete
statement
DDL:
◦ DDL triggers run when events such as
creating, altering or dropping an object
occurs on the server
◦ Used for database administration
tasks such as auditing and controlling
object access.
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.
TRIGGERS CAN GET FIRED IN TWO
DIFFERENT MODES:
◦ For/After Trigger: It gets fired only after the sql server
completes all actions successfully on a specified table.
For example on inserting a row on a table, the trigger
defined on the INSERT operation fires only after the
row gets successfully inserted and if the insert fails sql
does not execute the trigger.
◦ Instead of Trigger: It causes the code present in the
trigger to execute instead of the operation that caused
the trigger to fire. If we define INSTEAD OF Trigger on
the above mentioned table, insert would not happen
but the trigger gets fired.
SYNTAX OF TRIGGERS:
◦ DML Trigger:
CREATE TRIGGER trigger_name
ON { table | view }
[ WITH ENCRYPTION ]
{
{ {FOR | AFTER | INSTEAD OF }
{ [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] }
AS
sql_statement [...n ]
}
}
ARGUMENTS:
◦ Trigger_name: Is the name of the trigger.
◦ Table | view: Is the table or view on which the trigger is
executed
◦ WITH ENCRYPTION: Code in the trigger will be
encrypted when it is created
◦ AFTER: Specifies that the trigger is fired only when all
operations specified in the triggering SQL statement
have executed successfully
◦ INSTEAD OF: Specifies that the trigger is executed
instead of the triggering SQL statement
◦ { [DELETE] [,] [INSERT] [,] [UPDATE] }: Are keywords
that specify which data modification statements, when
attempted against the table or view, activate the
trigger.
DDL TRIGGERS SYNTAX:
CREATE TRIGGER trigger_name ON { ALL
SERVER | DATABASE }
[ WITH ENCRYPTION ]
{
{ {FOR | AFTER }
{ event_type | event_group } [ ,...n ]
AS
sql_statement [...n ]
}
}
ARGUMENTS:
◦ DATABASE: If specified, the trigger fires whenever
event_type or event_group occurs in the current
database.
◦ ALL SERVER: If specified, the trigger fires whenever
event_type or event_group occurs anywhere in the
current server.
◦ Event_type: Is the name of a Transact-SQL language
event that, after execution, causes a DDL trigger to fire.
(create, alter, drop)
◦ Event_group: The DDL trigger fires after execution of
any Transact-SQL language event that belongs to
event_group.
Thanks!

Mais conteúdo relacionado

Mais procurados

The sql connection object
The sql connection objectThe sql connection object
The sql connection objectSharat Chandu
 
Databases in Android Application
Databases in Android ApplicationDatabases in Android Application
Databases in Android ApplicationMark Lester Navarro
 
Android database tutorial
Android database tutorialAndroid database tutorial
Android database tutorialinfo_zybotech
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursorsinfo_zybotech
 
Android Database Tutorial
Android Database TutorialAndroid Database Tutorial
Android Database TutorialPerfect APK
 
Interface connection
Interface connectionInterface connection
Interface connectionmyrajendra
 
09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)Oum Saokosal
 
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code FirstJames Johnson
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile appsIvano Malavolta
 
Data Handning with Sqlite for Android
Data Handning with Sqlite for AndroidData Handning with Sqlite for Android
Data Handning with Sqlite for AndroidJakir Hossain
 
User controls
User controlsUser controls
User controlsaspnet123
 
SSMS-waitstats
SSMS-waitstatsSSMS-waitstats
SSMS-waitstatsE Blake
 
Persitance Data with sqlite
Persitance Data with sqlitePersitance Data with sqlite
Persitance Data with sqliteArif Huda
 

Mais procurados (20)

The sql connection object
The sql connection objectThe sql connection object
The sql connection object
 
Databases in Android Application
Databases in Android ApplicationDatabases in Android Application
Databases in Android Application
 
Database in Android
Database in AndroidDatabase in Android
Database in Android
 
Android database tutorial
Android database tutorialAndroid database tutorial
Android database tutorial
 
Accessing data with android cursors
Accessing data with android cursorsAccessing data with android cursors
Accessing data with android cursors
 
Android Database Tutorial
Android Database TutorialAndroid Database Tutorial
Android Database Tutorial
 
Interface connection
Interface connectionInterface connection
Interface connection
 
09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)09.1. Android - Local Database (Sqlite)
09.1. Android - Local Database (Sqlite)
 
Lecture13
Lecture13Lecture13
Lecture13
 
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code First
 
Android Database
Android DatabaseAndroid Database
Android Database
 
Android sq lite-chapter 22
Android sq lite-chapter 22Android sq lite-chapter 22
Android sq lite-chapter 22
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
 
Trigger
TriggerTrigger
Trigger
 
Data Handning with Sqlite for Android
Data Handning with Sqlite for AndroidData Handning with Sqlite for Android
Data Handning with Sqlite for Android
 
User controls
User controlsUser controls
User controls
 
SSMS-waitstats
SSMS-waitstatsSSMS-waitstats
SSMS-waitstats
 
Ssis event handler
Ssis event handlerSsis event handler
Ssis event handler
 
SQLITE Android
SQLITE AndroidSQLITE Android
SQLITE Android
 
Persitance Data with sqlite
Persitance Data with sqlitePersitance Data with sqlite
Persitance Data with sqlite
 

Semelhante a T-SQL & Triggers

7\9 SSIS 2008R2_Training - Script Task
7\9 SSIS 2008R2_Training - Script Task7\9 SSIS 2008R2_Training - Script Task
7\9 SSIS 2008R2_Training - Script TaskPramod Singla
 
Lecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML TriggersLecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML TriggersAlexey Furmanov
 
Tony Jambu (obscure) tools of the trade for tuning oracle sq ls
Tony Jambu   (obscure) tools of the trade for tuning oracle sq lsTony Jambu   (obscure) tools of the trade for tuning oracle sq ls
Tony Jambu (obscure) tools of the trade for tuning oracle sq lsInSync Conference
 
Performance tuning a quick intoduction
Performance tuning   a quick intoductionPerformance tuning   a quick intoduction
Performance tuning a quick intoductionRiyaj Shamsudeen
 
Sql server-performance-hafi
Sql server-performance-hafiSql server-performance-hafi
Sql server-performance-hafizabi-babi
 
ISAS On SQL Features like Trigger, Transaction,Batches, Stored Procedure
ISAS On SQL Features like Trigger, Transaction,Batches, Stored ProcedureISAS On SQL Features like Trigger, Transaction,Batches, Stored Procedure
ISAS On SQL Features like Trigger, Transaction,Batches, Stored ProcedureShubham Choudahry
 
Database Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event SchedulersDatabase Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event SchedulersAbdul Rahman Sherzad
 
Intro to tsql unit 14
Intro to tsql   unit 14Intro to tsql   unit 14
Intro to tsql unit 14Syed Asrarali
 
23 ijaprr vol1-3-25-31iqra
23 ijaprr vol1-3-25-31iqra23 ijaprr vol1-3-25-31iqra
23 ijaprr vol1-3-25-31iqraijaprr_editor
 
A set of SQL(structured query language) statements that are designat.pdf
A set of SQL(structured query language) statements that are designat.pdfA set of SQL(structured query language) statements that are designat.pdf
A set of SQL(structured query language) statements that are designat.pdfinfo430661
 

Semelhante a T-SQL & Triggers (20)

Sql triggers
Sql triggersSql triggers
Sql triggers
 
4 trigger
4  trigger4  trigger
4 trigger
 
7\9 SSIS 2008R2_Training - Script Task
7\9 SSIS 2008R2_Training - Script Task7\9 SSIS 2008R2_Training - Script Task
7\9 SSIS 2008R2_Training - Script Task
 
Lecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML TriggersLecture 4. MS SQL. DML Triggers
Lecture 4. MS SQL. DML Triggers
 
Trigger
TriggerTrigger
Trigger
 
Tony Jambu (obscure) tools of the trade for tuning oracle sq ls
Tony Jambu   (obscure) tools of the trade for tuning oracle sq lsTony Jambu   (obscure) tools of the trade for tuning oracle sq ls
Tony Jambu (obscure) tools of the trade for tuning oracle sq ls
 
Performance tuning a quick intoduction
Performance tuning   a quick intoductionPerformance tuning   a quick intoduction
Performance tuning a quick intoduction
 
Sql server-performance-hafi
Sql server-performance-hafiSql server-performance-hafi
Sql server-performance-hafi
 
ISAS On SQL Features like Trigger, Transaction,Batches, Stored Procedure
ISAS On SQL Features like Trigger, Transaction,Batches, Stored ProcedureISAS On SQL Features like Trigger, Transaction,Batches, Stored Procedure
ISAS On SQL Features like Trigger, Transaction,Batches, Stored Procedure
 
Database Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event SchedulersDatabase Automation with MySQL Triggers and Event Schedulers
Database Automation with MySQL Triggers and Event Schedulers
 
Trigger
TriggerTrigger
Trigger
 
Intro to tsql unit 14
Intro to tsql   unit 14Intro to tsql   unit 14
Intro to tsql unit 14
 
Intro to tsql
Intro to tsqlIntro to tsql
Intro to tsql
 
Triggers
TriggersTriggers
Triggers
 
23 ijaprr vol1-3-25-31iqra
23 ijaprr vol1-3-25-31iqra23 ijaprr vol1-3-25-31iqra
23 ijaprr vol1-3-25-31iqra
 
A set of SQL(structured query language) statements that are designat.pdf
A set of SQL(structured query language) statements that are designat.pdfA set of SQL(structured query language) statements that are designat.pdf
A set of SQL(structured query language) statements that are designat.pdf
 
Sql saturday oc 2019
Sql saturday oc 2019Sql saturday oc 2019
Sql saturday oc 2019
 
SQL Tunning
SQL TunningSQL Tunning
SQL Tunning
 
triggers.pptx
triggers.pptxtriggers.pptx
triggers.pptx
 
Sql server
Sql serverSql server
Sql server
 

Mais de Ayesha Maqsood

Mais de Ayesha Maqsood (6)

Mvc, mvp & mvvm (erp)
Mvc, mvp & mvvm (erp)Mvc, mvp & mvvm (erp)
Mvc, mvp & mvvm (erp)
 
online privacy
online privacyonline privacy
online privacy
 
Child labor in Pakistan
Child labor in PakistanChild labor in Pakistan
Child labor in Pakistan
 
Perception
PerceptionPerception
Perception
 
Frame relay
Frame relayFrame relay
Frame relay
 
Precis writing
Precis writingPrecis writing
Precis writing
 

Último

Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsArshad QA
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...Health
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...masabamasaba
 
tonesoftg
tonesoftgtonesoftg
tonesoftglanshi9
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...panagenda
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...masabamasaba
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in sowetomasabamasaba
 
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT  - Elevating Productivity in Today's Agile EnvironmentHarnessing ChatGPT  - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT - Elevating Productivity in Today's Agile EnvironmentVictorSzoltysek
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is insideshinachiaurasa2
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionOnePlan Solutions
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfkalichargn70th171
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfonteinmasabamasaba
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastPapp Krisztián
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnAmarnathKambale
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️Delhi Call girls
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrainmasabamasaba
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...Jittipong Loespradit
 

Último (20)

Software Quality Assurance Interview Questions
Software Quality Assurance Interview QuestionsSoftware Quality Assurance Interview Questions
Software Quality Assurance Interview Questions
 
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
+971565801893>>SAFE AND ORIGINAL ABORTION PILLS FOR SALE IN DUBAI AND ABUDHAB...
 
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
%+27788225528 love spells in Atlanta Psychic Readings, Attraction spells,Brin...
 
tonesoftg
tonesoftgtonesoftg
tonesoftg
 
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
W01_panagenda_Navigating-the-Future-with-The-Hitchhikers-Guide-to-Notes-and-D...
 
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
%+27788225528 love spells in Boston Psychic Readings, Attraction spells,Bring...
 
%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto%in Soweto+277-882-255-28 abortion pills for sale in soweto
%in Soweto+277-882-255-28 abortion pills for sale in soweto
 
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT  - Elevating Productivity in Today's Agile EnvironmentHarnessing ChatGPT  - Elevating Productivity in Today's Agile Environment
Harnessing ChatGPT - Elevating Productivity in Today's Agile Environment
 
The title is not connected to what is inside
The title is not connected to what is insideThe title is not connected to what is inside
The title is not connected to what is inside
 
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) SolutionIntroducing Microsoft’s new Enterprise Work Management (EWM) Solution
Introducing Microsoft’s new Enterprise Work Management (EWM) Solution
 
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdfPayment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
Payment Gateway Testing Simplified_ A Step-by-Step Guide for Beginners.pdf
 
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
%in Stilfontein+277-882-255-28 abortion pills for sale in Stilfontein
 
WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?WSO2CON 2024 - Does Open Source Still Matter?
WSO2CON 2024 - Does Open Source Still Matter?
 
Architecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the pastArchitecture decision records - How not to get lost in the past
Architecture decision records - How not to get lost in the past
 
VTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learnVTU technical seminar 8Th Sem on Scikit-learn
VTU technical seminar 8Th Sem on Scikit-learn
 
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
call girls in Vaishali (Ghaziabad) 🔝 >༒8448380779 🔝 genuine Escort Service 🔝✔️✔️
 
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With SimplicityWSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
WSO2Con2024 - Enabling Transactional System's Exponential Growth With Simplicity
 
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
Abortion Pill Prices Tembisa [(+27832195400*)] 🏥 Women's Abortion Clinic in T...
 
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
%in Bahrain+277-882-255-28 abortion pills for sale in Bahrain
 
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
MarTech Trend 2024 Book : Marketing Technology Trends (2024 Edition) How Data...
 

T-SQL & Triggers

  • 2. T-SQL T-SQL (Transact-SQL) is a set of programming extensions from Sybase and Microsoft that add several features to the Structured Query Language (SQL), including transaction control, exception and error handling, row processing and declared variables. T-SQL (Transact-SQL) is an extension of SQL language.
  • 3. 1. Stored Procedure "A stored procedure is a set of Structured Query Language (SQL) statements with an assigned name, which are stored in a relational database management system as a group, so it can be reused and shared by multiple programs.” A stored procedure is simply a compiled database object that contains one or more T-SQL statements. T-SQL Statement Examples
  • 4. SQL Statements vs Stored Procedure First Time - Check syntax - Compile - Execute - Return data Second Time - Check syntax - Compile - Execute - Return data Creating - Check syntax - Compile First Time - Execute - Return data Second Time - Execute - Return data
  • 5. Create Stored Procedure CREATE PROC[EDURE] procedure_name [ @parameter_name data_type] [= default] [OUTPUT] [,...,n] AS T-SQL_statement(s)
  • 6. Example 1 (Without Parameters) Create procedure sp_customerList AS BEGIN SELECT customer_id, customer_name, customer_address FROM tbl_customer ORDER BY customer_name ASC END
  • 7. Example 2 (With Parameters) IF (object_id (‘InsertCustomer’)) is NOT NULL DROP PROCEDURE InsertCustomer GO CREATE PROCEDURE InsertCustomer @FisrtName varchar(15), @LastName varchar(15), @Address varchar(50) AS --Sectionn 1: Define and initialize the local variable. DECLARE @count int SELECT @count = 0 --Section 2: Determine whether the record already exists SELECT @count = COUNT(*) FROM tbl_customer WHERE FirstName = @FirstName AND LastName = @LastName --Section 3: Insert the record if it doesn’t exists IF (@count = 0) BEGIN INSER INTO tbl_customer VALUES (@FirsstNmae, @LastName, @Address) PRINT ‘Customer record inserted’ END ELSE PRINT ‘Customer record already exists…’ GO
  • 8. How to Execute Stored Procedures EXEC InsertCustomer @FirstName = ‘abc’, @LastName = ‘xyz’, @Address = ‘Pakistan’
  • 9. Alter Stored Procedure ALTER PROC[EDURE] procedure_name [ @parameter_name data_type] [= default] [OUTPUT] [,...,n] AS t-sql_statement(s)
  • 10. Delete Stored Procedure DROP PROCEDURE procedure_name
  • 11. Stored Procedure Offers Many Advantages • You can avoid having to store all your T-SQL code in files. Stored procedures are stored in the database itself, so you never have to search through files to find the code you want to use. • Stored procedure allows Faster Execution. • If you have a report that needs to be run frequently, you can create a stored procedure that produces the report. Anyone who has access to the database and permission to execute the stored procedure will be able to produce the report at will. • Stored Procedure provide better Security to your data. • Stored procedure reduces network traffic.
  • 13. 2. Trigger? ◦ Triggers are stored programs, which are automatically executed or fired when some events occur. ◦ We can define a Trigger as "A Trigger is a Database object just like a stored procedure or we can say it is a special kind of Stored Procedure which fires when an event occurs in a database.” ◦ User cannot fire the trigger explicitly, it gets fired implicitly on the basis of certain specified event.
  • 14. Example of Trigger: ◦ If you write a letter to your friend and then drop it in a mailbox without putting enough postage on the envelope, you trigger the post office to return the letter to you along with a friendly reminder that you need to add postage. This reminder is triggered by the lack of a stamp; otherwise, the letter would have gone through the mail without any delays.
  • 15. Types of Triggers: ◦ Generally there are three types of triggers available in sequel sever. i. DML(Data Manipulating Language) ii. DDL(Data Definition Language) iii. Logon Triggers
  • 16. DML: ◦ DML triggers run when insert, update or delete statements modify data in the specified table or view. i. Insert : triggers are invoked by insert statement ii. Update: triggers are invoked by update statement iii. Delete : triggers are invoked by delete statement
  • 17. DDL: ◦ DDL triggers run when events such as creating, altering or dropping an object occurs on the server ◦ Used for database administration tasks such as auditing and controlling object access.
  • 18. 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.
  • 19. TRIGGERS CAN GET FIRED IN TWO DIFFERENT MODES: ◦ For/After Trigger: It gets fired only after the sql server completes all actions successfully on a specified table. For example on inserting a row on a table, the trigger defined on the INSERT operation fires only after the row gets successfully inserted and if the insert fails sql does not execute the trigger. ◦ Instead of Trigger: It causes the code present in the trigger to execute instead of the operation that caused the trigger to fire. If we define INSTEAD OF Trigger on the above mentioned table, insert would not happen but the trigger gets fired.
  • 20. SYNTAX OF TRIGGERS: ◦ DML Trigger: CREATE TRIGGER trigger_name ON { table | view } [ WITH ENCRYPTION ] { { {FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] } AS sql_statement [...n ] } }
  • 21. ARGUMENTS: ◦ Trigger_name: Is the name of the trigger. ◦ Table | view: Is the table or view on which the trigger is executed ◦ WITH ENCRYPTION: Code in the trigger will be encrypted when it is created ◦ AFTER: Specifies that the trigger is fired only when all operations specified in the triggering SQL statement have executed successfully ◦ INSTEAD OF: Specifies that the trigger is executed instead of the triggering SQL statement ◦ { [DELETE] [,] [INSERT] [,] [UPDATE] }: Are keywords that specify which data modification statements, when attempted against the table or view, activate the trigger.
  • 22. DDL TRIGGERS SYNTAX: CREATE TRIGGER trigger_name ON { ALL SERVER | DATABASE } [ WITH ENCRYPTION ] { { {FOR | AFTER } { event_type | event_group } [ ,...n ] AS sql_statement [...n ] } }
  • 23. ARGUMENTS: ◦ DATABASE: If specified, the trigger fires whenever event_type or event_group occurs in the current database. ◦ ALL SERVER: If specified, the trigger fires whenever event_type or event_group occurs anywhere in the current server. ◦ Event_type: Is the name of a Transact-SQL language event that, after execution, causes a DDL trigger to fire. (create, alter, drop) ◦ Event_group: The DDL trigger fires after execution of any Transact-SQL language event that belongs to event_group.