zoukankan      html  css  js  c++  java
  • MySQL: @variable vs. variable. Whats the difference?

     

    In another question I posted someone told me that there is a difference between:

    @variable

    and:

    variable

    in MySQL. He also mentioned how MSSQL has batch scope and MySQL has session scope. Can someone elaborate on this for me?

     
     
    up vote445down voteaccepted

    MySQL has the concept of user-defined variables.

    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:

    SET @var = 1
    
    SELECT @var2 := 2

    When you develop a stored procedure in MySQL, you can pass the input parameters and declare the local variables:

    DELIMITER //
    
    CREATE PROCEDURE prc_test (var INT)
    BEGIN
        DECLARE  var2 INT;
        SET var2 = 1;
        SELECT  var2;
    END;
    //
    
    DELIMITER ;

    These variables are not prepended with any prefixes.

    The difference between a procedure variable and a session-specific user-defined variable is that procedure variable is reinitialized to NULL each time the procedure is called, while the session-specific variable is not:

    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-specific variable) is not.

    (In addition to user-defined variables, MySQL also has some predefined "system variables", which may be "global variables" such as @@global.port or "session variables" such as @@session.sql_mode; these "session variables" are unrelated to session-specific user-defined variables.)

  • 相关阅读:
    poj 1286 Necklace of Beads poj 2409 Let it Bead HDU 3923 Invoker <组合数学>
    大圣降妖录破解
    dex文件格式二
    dex文件格式一
    打造smali代码库辅助分析
    一键调试脚本使用手册
    TraceView进行性能分析
    Android Killer工具用法
    十三. JEB破解三
    十二. 一步步破解JEB 2.0demo版二
  • 原文地址:https://www.cnblogs.com/kungfupanda/p/5855158.html
Copyright © 2011-2022 走看看