5
What is a Trigger? A trigger is a SQL block structure which is fired when a DML statements like Insert, Delete, Update is executed on a database table. A trigger is triggered automatically when an associated DML statement is executed. Syntax: CREATE [OR REPLACE ] TRIGGER trigger_name {BEFORE | AFTER | INSTEAD OF } {INSERT [OR] | UPDATE [OR] | DELETE} [OF col_name] ON table_name [REFERENCING OLD AS o NEW AS n] [FOR EACH ROW] WHEN (condition) BEGIN --- sql statements END; CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates a trigger with the given name or overwrites an existing trigger with the same name. {BEFORE | AFTER | INSTEAD OF } - This clause indicates at what time should the trigger get fired. i.e for example: before or after updating a table. INSTEAD OF is used to create a trigger on a view. before and after cannot be used to create a trigger on a view. {INSERT [OR] | UPDATE [OR] | DELETE} - This clause determines the triggering event. More than one triggering events can be used together separated by OR keyword. The trigger gets fired at all the specified triggering event. [OF col_name] - This clause is used with update triggers. This clause is used when you want to trigger an event only when a specific column is updated. CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates a trigger with the given name or overwrites an existing trigger with the same name. [ON table_name] - This clause identifies the name of the table or view to which the trigger is associated. [REFERENCING OLD AS o NEW AS n] - This clause is used to reference the old and new values of the data being changed. By default, you reference the values as :old.column_name or :new.column_name. The reference names can also be changed from old (or new) to any other user-defined name. You cannot reference old values when inserting a record, or new values when deleting a record, because they do not exist.

DBMS Preparation

Embed Size (px)

Citation preview

7/30/2019 DBMS Preparation

http://slidepdf.com/reader/full/dbms-preparation 1/5

What is a Trigger?

A trigger is a SQL block structure which is fired when a DML statements like

Insert, Delete, Update is executed on a database table. A trigger is triggered

automatically when an associated DML statement is executed.

Syntax:

CREATE [OR REPLACE ] TRIGGER trigger_name{BEFORE | AFTER | INSTEAD OF }{INSERT [OR] | UPDATE [OR] | DELETE}[OF col_name]ON table_name[REFERENCING OLD AS o NEW AS n][FOR EACH ROW]WHEN (condition)BEGIN--- sql statements

END;

• CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates atrigger with the given name or overwrites an existing trigger with thesame name.

• {BEFORE | AFTER | INSTEAD OF } - This clause indicates at what timeshould the trigger get fired. i.e for example: before or after updating atable. INSTEAD OF is used to create a trigger on a view. before andafter cannot be used to create a trigger on a view.

• {INSERT [OR] | UPDATE [OR] | DELETE} - This clause determines thetriggering event. More than one triggering events can be used togetherseparated by OR keyword. The trigger gets fired at all the specifiedtriggering event.

• [OF col_name] - This clause is used with update triggers. This clause isused when you want to trigger an event only when a specific column isupdated.

• CREATE [OR REPLACE ] TRIGGER trigger_name - This clause creates atrigger with the given name or overwrites an existing trigger with thesame name.

• [ON table_name] - This clause identifies the name of the table or viewto which the trigger is associated.

[REFERENCING OLD AS o NEW AS n] - This clause is used to referencethe old and new values of the data being changed. By default, youreference the values as :old.column_name or :new.column_name. Thereference names can also be changed from old (or new) to any otheruser-defined name. You cannot reference old values when inserting arecord, or new values when deleting a record, because they do notexist.

7/30/2019 DBMS Preparation

http://slidepdf.com/reader/full/dbms-preparation 2/5

• [FOR EACH ROW] - This clause is used to determine whether a triggermust fire when each row gets affected ( i.e. a Row Level Trigger) or just once when the entire sql statement is executed(i.e.statement level Trigger).

• WHEN (condition) - This clause is valid only for row level triggers. The

trigger is fired only for rows that satisfy the condition specified.

For Example: The price of a product changes constantly. It is important tomaintain the history of the prices of the products.

We can create a trigger to update the 'product_price_history' table when theprice of the product is updated in the 'product' table.

1) Create the 'product' table and 'product_price_history' table

CREATE TABLE product_price_history(product_id number(5),product_name varchar2(32),supplier_name varchar2(32),unit_price number(7,2) );

CREATE TABLE product(product_id number(5),

product_name varchar2(32),supplier_name varchar2(32),unit_price number(7,2) ); 

2) Create the price_history_trigger and execute it.

CREATE or REPLACE TRIGGER price_history_triggerBEFORE UPDATE OF unit_priceON productFOR EACH ROWBEGININSERT INTO product_price_historyVALUES(:old.product_id,:old.product_name,:old.supplier_name,:old.unit_price);END;

7/30/2019 DBMS Preparation

http://slidepdf.com/reader/full/dbms-preparation 3/5

Advantages of using SQL trigger

• SQL Trigger provides an alternative way to check integrity.• SQL trigger can catch the errors in business logic in the database level.• SQL trigger provides an alternative way to run scheduled tasks. With

SQL trigger, you don’t have to wait to run the scheduled tasks. You canhandle those tasks before or after changes being made to databasetables.

• SQL trigger is very useful when you use it to audit the changes of datain a database table.

Disadvantages of using SQL trigger

• SQL trigger only can provide extended validation and cannot replaceall the validations. Some simple validations can be done in theapplication level. For example, you can validate input check in the

client side by using javascript or in the server side by server scriptusing PHP or ASP.NET.

• SQL Triggers executes invisibly from client-application which connectsto the database server so it is difficult to figure out what happenunderlying database layer.

• SQL Triggers run every updates made to the table therefore it addsworkload to the database and cause system runs slower.

7/30/2019 DBMS Preparation

http://slidepdf.com/reader/full/dbms-preparation 4/5

SQL Views

A VIEW is a virtual table, through which a selective portion of the data fromone or more tables can be seen. Views do not contain data of their own. Theyare used to restrict access to the database or to hide data complexity. A view

is stored as a SELECT statement in the database. DML operations on a viewlike INSERT, UPDATE, DELETE affects the data in the original table uponwhich the view is based.

CREATE VIEW view_nameASSELECT column_listFROM table_name [WHERE condition];

A view is nothing more than a SQL statement that is stored in the databasewith an associated name. A view is actually a composition of a table in the

form of a predefined SQL query.

A view can contain all rows of a table or select rows from a table. A view canbe created from one or many tables which depends on the written SQL queryto create a view.

Advantages

Views are used for several different reasons:

1. To hide data complexity. Instead of forcing your users to learn the T-SQL JOIN syntax you might wish to provide a view that runs acommonly requested SQL statement.

2. To protect the data. If you have a table containing sensitive data incertain columns, you might wish to hide those columns from certaingroups of users. For instance, customer names, addresses and theirsocial security numbers might all be stored in the same table;however, for lower level employees like shipping clerks, you can createa view that only displays customer name and address. You can grant

permissions to a view without allowing users to query the underlyingtables. There are a couple of ways you might want to secure your data: 

1. Create a view to allow reading of only certain columns from a table. Acommon example of this would be the salary column in the employee table. You might not want all personnel to be able to read manager's or eachother's salary. This is referred to as partitioning a table vertically and isaccomplished by specifying only the appropriate columns in the CREATE

7/30/2019 DBMS Preparation

http://slidepdf.com/reader/full/dbms-preparation 5/5

VIEW statement.

2. Create a view to allow reading only certain rows from a table. Forinstance, you might have a view for department managers. This way, eachmanager can provide raises only to the employees of his or her department.

 This is referred to as horizontal partitioning and is accomplished by providinga WHERE clause in the SELECT statement that creates a view.

2. Enforcing some simple business rules. For example, if you wish togenerate a list of customers that need to receive the fall catalog, youcan create a view of customers that have previously bought your shirtsduring the fall.

3. Data exports with BCP. If you are using BCP to export your SQL Serverdata into text files, you can format the data through views since BCP'sformatting ability is quite limited.

4. Customizing data. If you wish to display some computed values orcolumn names formatted differently than the base table columns, youcan do so by creating views.

Disadvantages

Even though views can be a great tool for securing and customizing data,they can be slow. Indeed, they are not any faster than the query that definesthem. With SQL Server 2000, indexed views (also referred to as

"materialized" views) are supported to overcome this limitation.

Views can especially degrade the performance if they are based on otherviews. Therefore, it is recommended NOT to create views based on otherviews. All views should be created against base tables.