Mysql stored procedure case!

The following is an example of a simple MySQL stored procedure. This stored procedure 接受一个参数(用户ID), and 返回该用户的姓名.

First, you need to create the stored procedure:

DELIMITER //

CREATE PROCEDURE GetUserName (IN userId INT)
BEGIN
    DECLARE userName VARCHAR(255);
    SELECT name INTO userName FROM users WHERE id = userId;
    SELECT userName;
END//

DELIMITER ;

This is a stored procedure definition statement in a MySQL database.

It defines a stored procedure called "GetUserName" that accepts a parameter "userId" and returns the username that matches that user ID.

In the stored procedure definition statement, 首先use the DELIMITER // command 输入结束符更改为两个斜杠"//". This is because MySQL's default input terminator is a semicolon ";", but in the stored procedure definition statement, we need to use two slashes "//" as the input terminator.

然后, use the CREATE PROCEDURE command to define a stored procedure named "GetUserName". The procedure accepts an input parameter named "userId" and uses DECLARE to command 声明a variable named "userName", which is used to store the username that matches the input parameter.
接着, use the SELECT statement to query the user names matching the input parameters in the users table, and store the query results in the "userName" variable.
最后, use the SELECT statement to return query results. At the end of the stored procedure definition statement, use the DELIMITER ; command to change the input terminator to a semicolon ";" to restore the default input terminator.

Replenish:

If you want to use the default input terminator semicolon ";" in MySQL, you can directly use the semicolon ";" as the input terminator at the end of the SQL statement.
For example, the following is an SQL statement that uses the default input terminator:

CREATE PROCEDURE GetUserName (IN userId INT)
BEGIN
    DECLARE userName VARCHAR(255);
    SELECT name INTO userName FROM users WHERE id = userId;
    SELECT userName;
END;

To call this stored procedure, you use the CALL statement:

CALL GetUserName(1);

This will call GetUserNamethe stored procedure and pass it user ID 1. It will return the name of the user with ID 1.

Note that the actual application of stored procedures may be more complex, depending on your needs.

Guess you like

Origin blog.csdn.net/qq_58647634/article/details/133789125