32

I am trying to define and initialize a MySQL variable for a query.

I have the following:

declare @countTotal int;
SET @countTotal = select COUNT(*)
 from nGrams;

I am using MySQL in Netbeans and it tells me I have an error. What/where is my error?

How can I fix this?

CodeKingPlusPlus
  • 15,383
  • 51
  • 135
  • 216

4 Answers4

52

MySQL has two 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", per the wording in your question, 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;
Community
  • 1
  • 1
eggyal
  • 122,705
  • 18
  • 212
  • 237
8

Try this:-

 select @countTotal := COUNT(*) from nGrams;
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
  • 1
    I think you probably intended to use the [`:=` assignment operator](http://dev.mysql.com/doc/en/assignment-operators.html#operator_assign-value), rather than the [`=` equality operator](http://dev.mysql.com/doc/en/comparison-operators.html#operator_equal)? – eggyal Dec 02 '12 at 15:37
4

Function example:

DROP FUNCTION IF EXISTS test;

DELIMITER $$
CREATE FUNCTION test(in_number INT) RETURNS INT
    BEGIN
        DECLARE countTotal INT;
        SET countTotal = SELECT COUNT(*) FROM nGrams;
    RETURN countTotal + in_number;
END $$
DELIMITER ;
alditis
  • 4,633
  • 3
  • 49
  • 76
1

According to DECLARE Syntax, declare must be inside a begin...end block.

Olaf Dietsche
  • 72,253
  • 8
  • 102
  • 198