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?
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.
MySQL variable assignment There are two ways to assign a value to a user-defined variable. You can use either := or = as the assignment operator in the SET statement. For example, the statement assigns number 100 to the variable @counter. The second way to assign a value to a variable is to use the SELECT statement.
You can store a value in a user-defined variable in one statement and refer to it later in another statement. This enables you to pass values from one statement to another. User variables are written as @ var_name , where the variable name var_name consists of alphanumeric characters, . , _ , and $ .
A local variable is a type of variable that can be used where the scope and extent of the variable is within the method or statement block in which it is declared. It is used as an iteration variable in the foreach statement, exception variable in the specific-catch clause and resource variable in the using statement.
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 aBEGIN ... 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;
Try this:-
select @countTotal := COUNT(*) from nGrams;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With