Cant declare variable SQL

James Stevenson picture James Stevenson · Nov 10, 2011 · Viewed 13k times · Source

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 :)

Answer

Gustav Bertram picture Gustav Bertram · Nov 10, 2011

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.