15
MySQL •View •Store Procedure & Function •Trigger

View, Store Procedure & Function and Trigger in MySQL - Thaipt

Embed Size (px)

DESCRIPTION

 

Citation preview

MySQL

•View•Store Procedure & Function•Trigger

View•View is set of saved SELECT queries. Queries can be executed in view.•Structure:

CREATE VIEW view_name ASSELECT statement

Select statement you can query any tables or views existed in the db. Subquery cannot be included Any variables cannot be used Temporary tables or views cannot be used; any tables or views

which referred by views must exists. View cannot be associated with triggers

Example

CREATE VIEW NhanSu ASSELECT a.name, age, c.name as TenTinhFROM people as a join huyen as b ON a.huyen_id = b.idjoin tinh as c ON b.id_tinh = c.id;

Advantage and Disadvantage•Advantage

Sercurity Simply

•Disadvantage: Server resources (memory, process)

Function & Store Procedure•A programming scripts with embedded SQL which has been complied and can be executed by MySQL server.•With SP, application logic can be stored in database.

How to createCREATE FUNCTION name ([parameterlist]) RETURNS datatype [options] sqlcode CREATE PROCEDURE name ([parameterlist]) [options] sqlcode

•Drop function/ proceduce DROP FUNCTION [IF EXISTS] name DROP PROCEDURE [IF EXISTS] name

AdvantageDecrease scriptsMaintenanceBetter database security

Disadvantage•Lack of Portability•DB Server overload

DELIMITER $$

CREATE PROCEDURE film_in_stock(IN p_film_id INT, IN p_store_id INT, OUT p_film_count INT)READS SQL DATABEGIN SELECT inventory_id FROM inventory WHERE film_id = p_film_id AND store_id = p_store_id AND inventory_in_stock(inventory_id);

SELECT FOUND_ROWS() INTO p_film_count;END $$

DELIMITER ;

•DELIMITER $$: •Assign value:

Use SET or SELECT INTO.•Call proceduce:

Call film_in_stock(1,1, @film_count); Select @film_count;

Trigger•What is trigger?•These applications my include : save changes or updates other data tables.•Trigger run after updating table

•CREATE TRIGGER name BEFORE | AFTER INSERT |UPDATE | DELETE ON tablename

FOR EACH ROW sql-code

•DROP TRIGGER tablename.triggername •ALTER TRIGGER, SHOW CREATE TRIGGER, hoặc SHOW TRIGGER STATUS•Để hiển thị các trigger gắn với 1 bảng dữ liệu

SELECT * FROM Information_Schema.TriggerWHERE Trigger_schema = 'database_name' AND

Event_object_table = 'table_name';

How to create

DELIMITER ;;

CREATE TRIGGER `upd_film` AFTER UPDATE ON `film` FOR EACH ROW BEGIN IF (old.title != new.title) or (old.description != new.description) THEN UPDATE film_text SET title=new.title, description=new.description, film_id=new.film_id WHERE film_id=old.film_id; END IF; END;;DELIMITER ;

•Inside structure same as SP•In trigger, scripts can access columbs of current record.

OLD.columnname (UPDATE, DELETE) NEW.columnname (INSERT, UPDATE)