LAB08_ Data manipulation triggers and Stored procedures _Manual and Exercise_
LAB08_ Data manipulation triggers and Stored procedures _Manual and Exercise_
1
PROCEDURE 1 – How to create triggers.
Data manipulation triggers are sets of T-SQL statements that perform a specific action. They are often
referred to as a special kind of stored procedure. Unlike stored procedures, triggers are executed only
when a user or application attempts to modify data using Data Manipulation Language (DML). DML
includes INSERTs, UPDATEs, and DELETEs against views and tables.
The CREATE TRIGGER statement allows you to create a new trigger that is fired automatically
whenever an event such as INSERT, DELETE, or UPDATE occurs against a table.
You can use the following pseudocode sample script for creating a DML trigger:
WITH <Options>: In this argument you can specify additional options for the creation of the trigger.
FOR or AFTER [INSERT, UPDATE, DELETE]: These types of triggers are executed after the firing
statement ends (either an insert, update or delete).
INSTEAD OF [INSERT, UPDATE, DELETE]: Contrary to the FOR (AFTER) type, the INSTEAD OF triggers
executes instead of the firing statement. In other words, this type of trigger replaces the firing
statement. This is very useful in cases where you need to have cross database referential integrity.
[INSERT], [UPDATE], [DELETE]: The DML event (or list of events) that will cause the trigger to fire.
EXECUTE AS: Changes the security context on which the trigger will execute.
Note that; Constraints, including foreign-key cascade operations, are checked prior to executing either
type of trigger. If it is an INSTEAD OF trigger, the constraint is checked after the trigger completes. If
it is an AFTER trigger, the constraint is checked prior to executing the trigger. Regardless of the type
of trigger, when the trigger event is rolled back, it causes a constraint violation. For INSTEAD OF
triggers, the entire event is undone or rolled back, and in the case of FOR triggers, nothing is executed.
2
Step 1 - Create a trigger that checks the modified date. The trigger ensures that during the insert of a
new department, the modified date is the current day. If it is not, the row is updated, setting
ModifiedDate to the current date and time.
Note that; In the code of the trigger, specifically the SELECT statement, a logical table called inserted
is referenced. There are actually two tables of this type - the second table is deleted. These tables are
available within the context of the trigger. You cannot modify the structure or contents of these tables.
The inserted table stores a copy of a row or rows that were inserted, or a copy of the new values for
rows that were updated. During an update, the inserted table stores the new or updated data. The
second (deleted) table stores the data before an update and a row or rows that were deleted in a
DELETE statement.
3
** In the last row of the result set, you will see the newly inserted row. Notice that the modified date
is not the value that was specified in the insert. It should be the current date and time of the insert.
ALTER TRIGGER changes properties of an existing trigger. If you need to change the code of a single
trigger maybe the easiest way to do so is by using the ALTER TRIGGER statement.
You can use the following pseudocode sample script for altering a DML trigger:
Step 1 - Alter the HumanResources.iCheckModifedDate trigger that checks the modified date. The
trigger ensures that during the insert of a new department, the modified date is the current day. If it
is not, the row is updated, setting ModifiedDate to the yesterday's date and time.
4
Step 2 - Let’s insert a new data in Department table.
** In the last row of the results, you should see a modified date that is set to yesterday's date.
5
PROCEDURE 3 – How to enable, disable or drop triggers.
Step 1 - In some cases, you may not want to delete a trigger, but you want to stop it from firing during
a large. DML operation or for testing purposes SQL Server provides you with the ability to disable a
trigger, and once you have completed the task, you can enable the trigger again.
Step 2 - The SQL Server DROP TRIGGER statement drops one or more triggers from the database.
You can use the following pseudocode sample script for removing a DML trigger:
Stored procedures are a set of SQL statements (one or more) typically grouped together to perform a
specific routine. Stored procedures can be created in any user-defined database and system database
except the resource database. Some of the benefits of using stored procedures are as follows:
• They offer improved performance because of compiled code.
• They are easy to maintain because changes are central instead of inline with code.
• Since database operations can be performed inside the stored procedures, they provide a
strong level of security. Instead of access being granted to the underlying object, permission
can be granted only to the stored procedure. Essentially, stored procedures create a level of
abstraction for permissions—instead of the user being granted SELECT, INSERT, UPDATE, or
DELETE rights, the user can be granted EXECUTE rights to a stored procedure.
6
Step 1 - Let's create a simple store procedure that returns the PurchaseOrderID,
PurchaseOrderDetailID, OrderDate, TotalDue, ReceivedQty and ProductName information of the
products sold.
Step 2 - To execute a stored procedure using T-SQL, you use the EXECUTE or EXEC keyword.
7
Step 3 - To change the result set, you issue the EXECUTE command as normal, but you add a WITH
RESULT SETS statement, and within the parentheses you provide a new column definition for each
column in the result set.
** In the preceding query, the EXEC keyword is used for a standard stored procedure execution
However, the columns and data types have been changed to make the column names
user-friendly
Step 4 - Stored procedures can include parameters as part of their code. Creating a stored procedure
with parameters allows the calling programs to pass values into the procedure. If your stored
procedure contains a default parameter, you are not required to supply the DEFAULT keyword. If you
simply execute the stored procedure using the EXEC keyword, the assigned value will be used at run
time.
8
** In the first part of the SQL code, a stored procedure is created that has a single output parameter.
The output parameter includes the OUTPUT keyword. The stored procedure contains a single T-SQL
statement that assigns 10 to the parameter. In the second part of the code, a variable is declared that
will hold the value of the output parameter. The EXEC keyword is used to execute the stored
procedure. In addition, the declared variable is specified including the OUTPUT keyword. Finally, a
SELECT statement is issued to display the value of the output.
** In the preceding stored procedure, two parameters were specified: input and default. At the end
of the T-SQL query, a WHERE clause was included that limits the result based on the values of the two
parameters.
Step 2 – To execute this stored procedure, only the input parameter has been specified, which is fine
because the other parameter has a default value. To call this stored procedure we can execute it as
follows:
9
Step 3 - In the previous code, the default value for the OrderYear parameter has been overwritten
with 2012. To call this stored procedure we can execute it as follows:
Step 1 – To delete a stored procedure, you can use the DROP PROCEDURE statement
SUMMARY
In this LAB, you learned about triggers, which are associated to a specific table or view. In the event
of a DML operation on that table or view, the trigger will execute, performing some action. There are
three types of triggers: AFTER, INSTEAD OF, and FOR. This chapter focused on the AFTER and INSTEAD
OF triggers and their capabilities. Stored procedures are among the most robust programming tools
available in the Microsoft SQL Server database. As you learned in this LAB, you can use stored
procedures in several ways to accomplish many things.
10
PROCEDURE 7 – LAB EXERCISE
Consider the DentistDB database from CATS.
PROCEDURE 1: Create a trigger that lists the table, after the user adds a new record to the Dentists
table. The program also says ‘New Record!’ after a record is added to the table.
PROCEDURE 2: Create a Stored Procedure that deletes all records matching the CustomerID in
Customers table. Then, write an SQL statement that deletes the customer information with
CustomerID=20.
11