当前位置:网站首页>[MySQL] use of stored procedures

[MySQL] use of stored procedures

2022-06-11 10:25:00 Xiao AI ~

1. Use of stored procedures

Before using a stored procedure, learn what a stored procedure is .

 Stored procedures and functions 
 Stored procedures and functions : Be similar to java The method in  
 benefits :
1. Improve code reuse 
2. Simplified operation 

 meaning : A set of precompiled sql Collection of statements , Understand batch processing statements 
1. Improve code reuse 
2. Simplified operation 
3. The number of compilations is reduced and the connection to the database server is reduced , Improved efficiency .

The syntax of the stored procedure is :

 One 、 Create Syntax 
CREATE PROCEDURE helloWord()
BEGIN


END

 Be careful :
1. The parameter list consists of three parts 
 Parameter mode    Parameter name   Parameter type 
 give an example :
IN stuname VARCHAR(20)

 Parameter mode :
IN :  This parameter can be used as input , That is, the parameter requires the caller to pass in a value 
OUT: This generation can be used as an output , That is, the parameter can be used as the return value 
INOUT: Changing parameters can be input or output 

1. establish in Stored procedures for patterns

CREATE PROCEDURE myp2(IN `name` VARCHAR(20))
BEGIN
		DECLARE res INT DEFAULT 0; # Define variables and initialize 
		SELECT COUNT(*) INTO res # assignment 
		FROM tab_identity
		WHERE tab_identity.`NAME`=`name`;
		
		SELECT IF(res>0,' success ',' Failure ')  result ;
		
END

# Calling stored procedure 
CALL myp2(' Zhang Sanfeng ');

2. establish out Stored procedures for patterns


CREATE PROCEDURE myp4(IN `id` BIGINT(20),OUT boyName VARCHAR(20))
BEGIN
	SELECT ide.`NAME` INTO boyName
	FROM tab_identity ide
	WHERE ide.`ID`=id;
END

# Calling stored procedure 
CALL myp4(11,@bName);
SELECT @bName;

3. Create a inout Stored procedures for patterns


# Create a inOut Stored procedures for patterns 
CREATE PROCEDURE myp6(INOUT `id` INT)
BEGIN
	SET id=id*5;
END	

# with inout A variable needs to be created before the stored procedure call of 
SET @a=10;
CALL myp6(@a);
SELECT @a;


原网站

版权声明
本文为[Xiao AI ~]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/162/202206111022404915.html