2013年10月16日 星期三

MySQL: @variable vs. variable. Whats the difference?

http://stackoverflow.com/questions/1009954/mysql-variable-vs-variable-whats-the-difference


MySQL has concept of session variables.
The scope of this variable is the entire session. That means that while your connection with the database exists, the variable can still be used.

They are loosely typed variables that may be initialized somewhere in a session and keep their value until the session ends.

They are prepended with an @ sign, like this: @var

You can initialize this variable with a SET statement or inside in a query:

CREATE PROCEDURE prc_test ()
BEGIN
    DECLARE var2 INT DEFAULT 1;
    SET var2 := var2 + 1;
    SET @var2 := @var2 + 1;
    SELECT  var2, @var2;
END;

SET @var2 = 1;

CALL prc_test();

var2  @var2
---   ---
2     2


CALL prc_test();

var2  @var2
---   ---
2     3


CALL prc_test();

var2  @var2
---   ---
2     4

As you can see, var2 (procedure variable) is reinitialized each time the procedure is called, while @var2 (session variable) is not.

The scope of this variable is the entire session. That means that while your connection with the database exists, the variable can still be used.

沒有留言:

張貼留言