How to declare a variable in MySQL?

后端 未结 7 1784
春和景丽
春和景丽 2020-11-22 05:01

How to declare a variable in mysql, so that my second query can use it?

I would like to write something like:

SET start = 1;
SET finish = 10;

SELECT         


        
7条回答
  •  清歌不尽
    2020-11-22 05:32

    Different types of variable:

    • local variables (which are not prefixed by @) are strongly typed and scoped to the stored program block in which they are declared. Note that, as documented under DECLARE Syntax:

    DECLARE is permitted only inside a BEGIN ... END compound statement and must be at its start, before any other statements.

    • User variables (which are prefixed by @) are loosely typed and scoped to the session. Note that they neither need nor can be declared—just use them directly.

    Therefore, if you are defining a stored program and actually do want a "local variable", you will need to drop the @ character and ensure that your DECLARE statement is at the start of your program block. Otherwise, to use a "user variable", drop the DECLARE statement.

    Furthermore, you will either need to surround your query in parentheses in order to execute it as a subquery:

    SET @countTotal = (SELECT COUNT(*) FROM nGrams);

    Or else, you could use SELECT ... INTO:

    SELECT COUNT(*) INTO @countTotal FROM nGrams;

提交回复
热议问题