简体   繁体   中英

MySQL Stored Procedure Variables - When to Use Which

I am new to MySQL. When do we use declared variable? When to use undeclared variable (@varTest) .

I am wondering about the best practice. Thank you.

You should always create procedural variables with DECLARE to maintain proper scope. Session variables declared outside the function can be changed inside the function, and vice-versa.

DROP PROCEDURE IF EXISTS foo;
DELIMITER $

CREATE PROCEDURE foo()
    BEGIN
        DECLARE foo INT;
        SET foo = 123;
        SET @foo = 456;
        SELECT foo, @foo;
    END$

DELIMITER ;

SET @foo = "BAR";
CALL foo();
SELECT @foo;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM