Views, stored procedures, functions, triggers

MySQL Advanced

view

Views are stored in the database and can be reused. Data is not stored in views.

Define view

CREATE VIEW 视图名 AS SELECT 列 1,列 2... FROM 表(查询语句);
Use views
SELECT * FROM 视图名

Delete view
drop view 视图名

CREATE VIEW sel_news AS
SELECT
  n.id,
  n.title,
  t.type_name
FROM
  news n
  LEFT JOIN TYPE t
    ON n.typeid = t.typeid;

-- 使用视图
 SELECT
  *
FROM
  sel_news;

-- 删除视图 
 DROP VIEW sel_news

stored procedure

Knowledge of database: You can store data in tail units, use SQL language, and operate data

Java language can also be used in the database to have logical processing functions.

It has been written in advance and stored in the database. You can call it directly when using it.
Advantages: The process of processing a certain logic is directly stored in the database. It runs faster

Disadvantages: High dependence on database, poor portability

MySQL stored procedure definition

> 
>创建存储过程的语法格式
> 
> create procedure 存储过程名([in 变量名 类型,out 参数 2,…]>			 begin
> 
>	 [declare 变量名 类型 [DEFAULT];]
> 
>  存储过程语句块; 
> 
> 
> end;

Grammar analysis:
1. The parameters of stored procedures are divided into three types: in, out, and inout.

2.in represents the input parameter (in parameter by default), indicating that the value of the parameter must be specified by the calling program.

3.out represents the output parameter, which means that after the value of the parameter is calculated by the stored procedure, the calculation result of the out parameter is returned to the calling program.

4. Inout represents both an input parameter and an output parameter, which means that the value of the parameter can be specified by the calling program, and the calculation result of the inout parameter can be returned to the calling program.

5. The statements in the stored procedure must be included between begin and end.

6.Declare is used to declare variables. To assign a default value to a variable, use default. To change the variable value in a statement block, use set variable=value;

eg:

-- ------------------------------------存储过程--------------------------------------------------------------

DELIMITER $$
-- 创建存储过程
CREATE
    PROCEDURE demo1()
   
   -- 存储过程体
	BEGIN
	-- declare 用来声明变量
	DECLARE v_name VARCHAR(10) DEFAULT '';
	SET v_name = 'jim';
	SELECT v_name; -- 测试输出语句
	END$$
DELIMITER ;

-- 调用存储过程
CALL demo1();



-- 查询新闻类型为1的有几条 演示入参和出参
 DELIMITER $$

CREATE PROCEDURE type_count (IN p_typeid INT, OUT p_count INT) -- 存储过程体
 BEGIN
  SELECT
    COUNT (*) INTO p_count
  FROM
    news
  WHERE typeid = p_typeid;
  SELECT
    p_count;
END $$
DELIMITER;
-- 在一个存储过程中调用另一个存储过程
 CALL type_count (1, @p_count) 
 
 



-- 存储过程中逻辑判断 if  else
DELIMITER $$

CREATE PROCEDURE demo2 (IN p_day INT, OUT p_name VARCHAR (10))
BEGIN
  IF p_day = 0
  THEN SET p_name = "星期天";
  SELECT
    p_name;
  ELSEIF p_day = 1
  THEN
  SET p_name="星期一";
     SELECT p_name; 
  ELSE SET p_name= "无效日期";
  SELECT p_name;
  END IF;
END $$
DELIMITER;

CALL demo2 (0,@p_name);

-- 使用存储过程插入信息
DELIMITER $$
CREATE PROCEDURE save_admin (
  IN p_account VARCHAR (10),
  IN p_password VARCHAR (50),
  OUT p_result VARCHAR (10)
)BEGIN
  DECLARE v_count INT DEFAULT 0;
  SELECT COUNT(*) INTO v_count FROM admin WHERE account = p_account;
  IF v_count=0 THEN
  INSERT INTO admin (account,PASSWORD)VALUES(p_account,p_password);
  SET p_result = '保存成功';
  ELSE
  SET p_result = '账号已存在';
  SELECT p_result;
  END IF;
END $$
-- 测试CALL 
CALL save_admin ('001','123',@p_result)




DELIMITER $$
CREATE PROCEDURE saveUser (
  IN p_account VARCHAR (20),
  IN p_sex CHAR (1),
  OUT res_mark INT)
BEGIN
  DECLARE v_count INT DEFAULT 0;
  
  SELECT COUNT(*) INTO v_count
  FROM
    admin
  WHERE account = p_account;
  IF v_count =0
  THEN
  INSERT INTO admin (account,sex)
  VALUES
    (p_account,p_sex);
  SET res_mark = 0;
  ELSE SET res_mark = 1;
  END IF;  
END $$

-- 测试CALL 
CALL save_admin ('001','123',@res_mark)


function

Functions are similar to stored procedures, but functions are mainly used for queries


create function 函数名([参数列表]) returns 数据类型
begin  DECLARE 变量;

sql 语句;
return;
end;

Notice:

1. The parameter list contains two parts: parameter name and parameter type
2. Function body: there must be a return statement, if not, an error will be reported
3. There is only one sentence in the function body, you can omit begin end
4. Use the delimter statement to set the end mark The setting function can have no parameters SET GLOBAL log_bin_trust_function_creators=TRUE;

delete function

DROP FUNCTION function name
eg:

-- ------------------------------------------函数--------------------------------------------------------

-- 函数  不带参数的
DELIMITER $$

CREATE FUNCTION test() RETURNS INT 
BEGIN DECLARE v_num INT DEFAULT 0;
SELECT
  COUNT(*) INTO v_num
FROM
  admin;
RETURN v_num;
END $$
DELIMITER
-- 测试
SELECT test ();




-- 带参数的
DELIMITER $$

CREATE
    FUNCTION findType(p_type INT) RETURNS VARCHAR(10)
    BEGIN
DECLARE v_type VARCHAR(10) DEFAULT '';
IF p_type = 0 THEN
SET v_type = '超级管理员';
ELSE 
SET v_type = '管理员';
END IF;
RETURN v_type;
    END$$
    

SELECT account,id,findType(TYPE) FROM admin



DELIMITER $$

CREATE
    FUNCTION find_news_type(p_typeid INT) RETURNS VARCHAR(10)
    BEGIN
DECLARE v_type VARCHAR(10) DEFAULT '';
SELECT type_name INTO v_type FROM TYPE WHERE typeid = p_typeid;
RETURN v_type;
    END$$ 

SELECT id,title,find_news_type(typeid) FROM news

trigger

Similar to stored procedures, functions, related to tables, a bit like events

Automatically triggered before or after adding, modifying, or deleting a table

Triggers have the following characteristics:

1. Associated with the table

Triggers are defined on a specific table, which is called a trigger table.

2. Automatically activate triggers

When performing an INSERT, UPDATE, or DELETE operation on data in a table, if the

A trigger is defined for a specific action, which is automatically executed and cannot be undone.

3. Cannot be called directly

Unlike stored procedures, triggers cannot be called directly, nor can they pass or accept parameters.

4. As part of a transaction

The trigger and the statement that activates the trigger are treated as a single transaction, which can be obtained from the trigger.

Rollback anywhere.
Syntax rules for defining triggers:

 CREATE TRIGGER 触发器名称 触发时机 触发事件 
 
ON 表名称 

FOR EACH ROW -- 行级触发

 BEGIN
 
语句 

END;

Syntax analysis:

1. Trigger name: It is used to identify the trigger and is customized by the user.

2. Trigger timing: its value is before or after.

3. Trigger event: its values ​​are insert, update and delete

4. Table name: identifies the table name to create the trigger, that is, on which table the trigger is created.

5. Statement: It is the trigger program body. The trigger program can use begin and end as the beginning and end, and contains multiple statements in the middle;
eg:

-- 触发器
-- 在admin表中插入一条数据后自动更新admin_log表
DELIMITER $$

CREATE
    
    TRIGGER save_adminLog AFTER 
    INSERT
    ON admin
    FOR EACH ROW BEGIN
	INSERT INTO admin_log(id,account,oper_time) VALUES(new.id,new.account,NOW());
    END$$

DELIMITER ;

INSERT INTO admin(account,PASSWORD)VALUES('s001','1231');



-- 当admin表和role表的主键分别都是admin_role表的外键约束时,
-- 想要删除admin表或role表中的数据,必须先删除admin_role表中的关联关系
DELIMITER $$

CREATE
    TRIGGER delete_admin_role
     BEFORE
     DELETE
    ON admin
    FOR EACH ROW BEGIN
	DELETE FROM admin_role WHERE adminid= old.id;
    END$$

DELIMITER ;
DELETE FROM admin WHERE id=3

Guess you like

Origin blog.csdn.net/crraxx/article/details/122591250