Download presentation
Presentation is loading. Please wait.
Published byNeil Barnett Modified over 6 years ago
1
PROCEDURES, CONDITIONAL LOGIC, EXCEPTION HANDLING, TRIGGERS
DPT621S
2
Recap on previous lessons
PHASE 1 Install SQL Server 2012 Express Install a Sample Database Attach a Sample Database PHASE 2 Create an ERD Transform the ERD into the logical and physical design Create a database in a simple way Create tables, alter tables, drop/re-create tables in SQL Server PHASE 3 Create stored procedures / with input and output parameters Modify stored procedures Display the definitions of stored procedures Rename stored procedures Delete stored procedures Recap on previous lessons
3
Recap……. Creating a Stored Procedure
USE MyDatabase GO Begins a new batch CREATE PROCEDURE sp_Films AS BEGIN SELECT filmName, filmReleaseDate, filmTime FROM Films Order BY filmName ASC END Run code….. Find your stored procedure Execute your stored procedure (Highlight name and exe) Recap……. Creating a Stored Procedure
4
Recap……….. Modifying your Procedure
USE MyDatabase GO Begins a new batch ALTER PROCEDURE sp_Films AS BEGIN SELECT filmName, filmReleaseDate, filmTime FROM Films Order BY filmName DESC END Recap……….. Modifying your Procedure
5
Recap….. Deleting a Procedure
DROP Procudure sp_Films Recap….. Deleting a Procedure
6
CONDITION LOGIC IF...ELSE Statement
In SQL Server, the IF...ELSE statement is used to execute code when a condition is TRUE, or execute different code if the condition evaluates to FALSE. CONDITION LOGIC
7
Syntax IF condition {...statements to execute when condition is TRUE...} [ ELSE {...statements to execute when condition is FALSE...} ]
8
DECLARE @n INT = 1 IF @n = 1 PRINT ‘ONE’ ELSE IF @n = 2 PRINT ‘TWO’ ELSE PRINT ‘Wrong”
Example
9
the CASE statement has the functionality of an IF-THEN-ELSE statement
the CASE statement has the functionality of an IF-THEN-ELSE statement. You can use the CASE statement within a SQL statement. CASE statement
10
Syntax CASE expression WHEN value_1 THEN result_1 WHEN value_2 THEN result_2 ... WHEN value_n THEN result_n ELSE result END
11
CASE WHEN condition_1 THEN result_1 WHEN condition_2 THEN result_2
CASE WHEN condition_1 THEN result_1 WHEN condition_2 THEN result_2 ... WHEN condition_n THEN result_n ELSE result END
12
Example SELECT contact_id, CASE website_id WHEN 1 THEN 'TechOnTheNet.com' WHEN 2 THEN 'CheckYourMath.com' ELSE 'BigActivities.com' END FROM contacts;
13
CASE example SELECT contact_id, CASE WHEN website_id = 1 THEN 'TechOnTheNet.com' WHEN website_id = 2 THEN 'CheckYourMath.com' ELSE 'BigActivities.com' END FROM contacts;
14
One thing to note is that the ELSE condition within the CASE statement is optional.
SELECT contact_id, CASE WHEN website_id = 1 THEN 'TechOnTheNet.com' WHEN website_id = 2 THEN 'CheckYourMath.com' END With the ELSE clause omitted, if no condition was found to be true, the CASE statement would return NULL. CASE Statement ….
15
Controls the flow of your script should an error occur
Main Focus……….. Try …..Catch Constructs Error Functions Use stored Procedure for error handling Exception Handling
16
Try …..Catch Constructs Try …..Catch Construct has 2 parts
1. Try Block (Starts with: “BEGIN TRY” Ends with: “END TRY” statement) Begin Begin Try End Try End 2. Catch Block(Starts with: “BEGIN CATCH” Ends with: “END CATCH” statement) Begin Catch End Catch Try …..Catch Constructs
17
Guidelines Your try block should be followed by a catch block.
Begin Begin Try select ‘E’ End Try Begin Catch End Catch End Try and catch block must be within a batch, stored procedure or trigger Guidelines
18
Try….Catch constructs can be nested
Begin Begin Try SELECT ‘E’ SELECT ‘F’ End Try Begin Catch End Catch End You can have a nested try….catch block inside a try block or inside a catch block.
19
Error Functions which are provided by MS SQL server
They are used to capture error information. ERROR_NUMBER() returns the error number - type is int. ERROR_LINE() This returns the line number that caused error – type is int. ERROR_SEVERITY() returns the severity level of the error. –type is int. ERROR_STATE() returns the state number of the error. –type is int. ERROR_PROCEDURE() This returns the name of the stored procedure or trigger where the error occurred. –type is nvarchar(128) ERROR_MESSAGE() returns the full text of error message. The text includes the values supplied for any substitutable parameters. –type is nvarchar(4000). Error Functions which are provided by MS SQL server
20
Example BEGIN Select 5/0 END
You will get an error …..without try….catch block Example
21
BEGIN Begin Try select 5/ We put or statement inside the try…catch block End Try Begin Catch select ‘Error is handled’ --so you can show any custom msg. End Catch END
22
We can use the build in functions to get the error details.
BEGIN Begin Try select 5/ We put or statement inside the try…catch block End Try Begin Catch select ERROR_LINE(), ERROR_MESSAGE(), ERROR_NUMBER(), ERROR_PROCEDURE() as Proc ERROR_SEVERITY(), ERROR_STATE() End Catch END
23
Your result will show the procedure name where the error occurred.
Now we write the code in a procedure CREATE PROCEDURE ErrorProcedure As BEGIN Begin Try select 5/ We put or statement inside the try…catch block End Try Begin Catch select ERROR_LINE(), ERROR_MESSAGE(), ERROR_NUMBER(), ERROR_PROCEDURE() as Proc ERROR_SEVERITY(), ERROR_STATE() End Catch END Now execute your Procedure: Exec ErrorProcedure Your result will show the procedure name where the error occurred.
24
Create a common code to handle/Store Errors
Exercise
25
Answer to exercise CREATE PROCEDURE ErrorHandler As BEGIN END
Use a common stored procedure to handle errors - Create a new procedure - Use the stored procedure to handle errors Step 1: CREATE PROCEDURE ErrorHandler As BEGIN select ERROR_LINE(), ERROR_MESSAGE(), ERROR_NUMBER(), ERROR_PROCEDURE() as ERROR_SEVERITY(), ERROR_STATE() END Answer to exercise
26
Alter PROCEDURE ErrorProcedure As BEGIN
Step 2: Alter your procedure Alter PROCEDURE ErrorProcedure As BEGIN Begin Try select 5/ We put or statement inside the try…catch block End Try Begin Catch Exec ErrorHandler --Call the error handling procedure End Catch END --Run your code Exec ErrorProcedure --Execute your procedure
27
TRIGGERS Is a special kind of procedure……
DML triggers (Table events: insert, update and delete associated with tables or views) Can be AFTER or INSTEAD OF You should know which table or view you want to attach the trigger to. TRIGGERS
28
-- SQL Server Syntax Trigger on an INSERT, UPDATE, or DELETE statement to a table or view (DML Trigger) CREATE TRIGGER [ schema_name . ]trigger_name ON { table | view } [ WITH <dml_trigger_option> [ ,...n ] ] { FOR | AFTER | INSTEAD OF } { [ INSERT ] [ , ] [ UPDATE ] [ , ] [ DELETE ] } [ WITH APPEND ] [ NOT FOR REPLICATION ] AS { sql_statement [ ; ] [ ,...n ] | EXTERNAL NAME <method specifier [ ; ] > } <dml_trigger_option> ::= [ ENCRYPTION ] [ EXECUTE AS Clause ] <method_specifier> ::= assembly_name.class_name.method_name Trigger Syntax
29
Example: CREATING A ‘AFTER’ Trigger
Use AdvantureWorks -- your database Go Create Trigger MyContacts ON Contacts --Which table or view the trigger is created for AFTER insert, update, delete -- After which event? You can have 1 or more events AS BEGIN --What do we want our trigger to do? -- We can print a msg to say something happened to our Contacts table Print ‘something happened to our Contacts table’ END GO Run your code……………………… Completed successfully
30
We need to trigger our insert or update or delete events in our table Contacts.
INSERT Into Contacts(list of columns,….) Values(list of values, …) --Update UPDATE Contacts SET DOD = GETDATE() Date of death WHERE ID = 999 --Delete DELETE FROM CONTACTS Execute your code…. 3 messages will be displayed Test Trigger
31
Modify your trigger Use AdvantureWorks -- your database Go
ALTER Trigger MyContacts ON Contacts --Which table or view the trigger is created for AFTER insert, undate, delete -- After which event? You can have 1 or more events AS BEGIN --What do we want our trigger to do? -- We can print a msg to say something happened to our Contacts table Print ‘Data was changed in the Contacts table’ END GO Modify your trigger
32
Use AdvantureWorks -- your database Go Drop Trigger MyContacts
Delete your Trigger
33
EXAMPLE: Create a INSTEAD OF Trigger
Use AdvantureWorks -- your database Go Create Trigger MyContactsTwo ON Contacts --Which table or view the trigger is created for INSTEAD OF insert -- After which event? You can have 1 or more events AS BEGIN --Custom error message with msg, severity and state RAISERROR (‘No more contacts can be inserted, 16, 1) END GO Run your code……………………… Completed successfully Now test the code EXAMPLE: Create a INSTEAD OF Trigger
34
USE AdventureWorks GO INSERT INTO Contacts(list of columns,….) Values(list of values, …) SELECT * FROM Contacts WHERE ID = 999 --Will not return any records Error msg will be displayed
35
Exercise Create a trigger to validate data in your database.
You have created a date of death for this contact so you want to make sure any update is valid. The criteria is: our trigger should check that the ID you provide for the person’s DOD is not null then the trigger should stop the event. Exercise
36
Answer Use AdvantureWorks -- your database Go
Step 1: Create a new trigger Use AdvantureWorks -- your database Go Create Trigger CastContact ON Contacts --Which table or view the trigger is created for AFTER insert -- After which event? You can have 1 or more events AS BEGIN --Custom error message with msg, severity and state IF EXIST( SELECT * FROM Contacts AS a INNER JOIN insertedTabl AS I ON a.ID = i.CastID WHERE DOD IS NOT NULL) BEGIBN RAISERROR(‘ Sorry but that person has expired’, 16, 1) ROLLBACK TRANSACTION -- This will cancel the insert if it happened. RETURN If I don’t want the procedure to end END GO Execute script…… Test your trigger by trying to insert some data…..using the deceased person
Similar presentations
© 2025 SlidePlayer.com. Inc.
All rights reserved.