Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Cant declare variable SQL

I've been trying to declare an integer variable but its just not working. Here is my query:

DECLARE @count INT
SET     @count = 5633

SELECT count(matchid) 
FROM   `matches`
WHERE   id = @count

Im getting this error:

Error Code: 1064. You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'DECLARE @count INT
SET     @count = 5633

Please help :)

like image 822
James Stevenson Avatar asked Nov 10 '11 13:11

James Stevenson


People also ask

How do you DECLARE a variable in SQL?

Variables in SQL procedures are defined by using the DECLARE statement. Values can be assigned to variables using the SET statement or the SELECT INTO statement or as a default value when the variable is declared. Literals, expressions, the result of a query, and special register values can be assigned to variables.

How add variable in SQL query?

The syntax for assigning a value to a SQL variable within a SELECT query is @ var_name := value , where var_name is the variable name and value is a value that you're retrieving. The variable may be used in subsequent queries wherever an expression is allowed, such as in a WHERE clause or in an INSERT statement.

Does DECLARE work in MySQL?

MySQL allows you to declare two or more variables that share the same data type using a single DECLARE statement. The following example declares two integer variables x and y , and set their default values to zero.

What is @@ variable in SQL?

In SQL Server, symbol @@ is prefixed to global variables. The server maintains all the global variables.


2 Answers

According to the MySQL manual, DECLARE is only allowed inside a BEGIN ... END block, and must be at the start. You're also forgetting a semicolon on the end of each line. This should work for you:

SET @count = 5633;

SELECT count(*) 
FROM matches
WHERE id = @count;

COUNT(*) is faster in some cases.

like image 121
Gustav Bertram Avatar answered Oct 23 '22 05:10

Gustav Bertram


DECLARE @count INT;
SET     @count = 5633;

SELECT count(matchid) 
FROM   matches
WHERE   id = @count;

Also, you apparently need a begin/end block.

like image 1
Dave Avatar answered Oct 23 '22 06:10

Dave