“@” symbol in stored procedure?

前端 未结 1 797
野趣味
野趣味 2021-01-15 17:38

I tried finding an answer to this online, but could not find any clear explanation:

Does the @ in a stored procedure serve some sort of special purpose/signify somet

相关标签:
1条回答
  • 2021-01-15 17:50

    The @variable syntax in MySQL denotes a user-defined session variable. You can set these user variables outside a stored procedure, but you can also set them inside a stored procedure, and the effect is that the variable retains the value after your procedure call returns.

    So in your example, the following would also do the same thing:

    CREATE PROCEDURE emp_count_2()
    BEGIN
     SELECT COUNT(*) INTO @empCount FROM Employee;
    END
    
    CALL emp_count_2(); /* sets @empCount as a side-effect */
    SELECT @empCount;
    

    It's okay for multiple sessions to set the user variable in this way concurrently, because user variables are scoped to a single session, and concurrent sessions may have variables of the same name, but with different values.

    The variable syntax with no @ prefix is for variables local to the procedure, either procedure parameters, or else local variables declared with DECLARE within the procedure body.

    This usage you have, passing a user variable as a parameter and assigning it in the body of the procedure, is useful if you want to call a procedure several times and store the result in separate user variables. Otherwise each call to the procedure would overwrite the previous value in the @empCount user variable for the current session.

    0 讨论(0)
提交回复
热议问题