DBeaver declare statement for MySQL is failing [duplicate] - mysql

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 * FROM places WHERE place BETWEEN start AND finish;

There are mainly three types of variables in MySQL:
User-defined variables (prefixed with #):
You can access any user-defined variable without declaring it or
initializing it. If you refer to a variable that has not been
initialized, it has a value of NULL and a type of string.
SELECT #var_any_var_name
You can initialize a variable using SET or SELECT statement:
SET #start = 1, #finish = 10;
or
SELECT #start := 1, #finish := 10;
SELECT * FROM places WHERE place BETWEEN #start AND #finish;
User variables can be assigned a value from a limited set of data
types: integer, decimal, floating-point, binary or nonbinary string,
or NULL value.
User-defined variables are session-specific. That is, a user
variable defined by one client cannot be seen or used by other
clients.
They can be used in SELECT queries using Advanced MySQL user variable techniques.
Local Variables (no prefix) :
Local variables needs to be declared using DECLARE before
accessing it.
They can be used as local variables and the input parameters
inside a stored procedure:
DELIMITER //
CREATE PROCEDURE sp_test(var1 INT)
BEGIN
DECLARE start INT unsigned DEFAULT 1;
DECLARE finish INT unsigned DEFAULT 10;
SELECT var1, start, finish;
SELECT * FROM places WHERE place BETWEEN start AND finish;
END; //
DELIMITER ;
CALL sp_test(5);
If the DEFAULT clause is missing, the initial value is NULL.
The scope of a local variable is the BEGIN ... END block within
which it is declared.
Server System Variables (prefixed with ##):
The MySQL server maintains many system variables configured to a default value.
They can be of type GLOBAL, SESSION or BOTH.
Global variables affect the overall operation of the server whereas session variables affect its operation for individual client connections.
To see the current values used by a running server, use the SHOW VARIABLES statement or SELECT ##var_name.
SHOW VARIABLES LIKE '%wait_timeout%';
SELECT ##sort_buffer_size;
They can be set at server startup using options on the command line or in an option file.
Most of them can be changed dynamically while the server is running using SET GLOBAL or SET SESSION:
-- Syntax to Set value to a Global variable:
SET GLOBAL sort_buffer_size=1000000;
SET ##global.sort_buffer_size=1000000;
-- Syntax to Set value to a Session variable:
SET sort_buffer_size=1000000;
SET SESSION sort_buffer_size=1000000;
SET ##sort_buffer_size=1000000;
SET ##local.sort_buffer_size=10000;

SET
SET #var_name = value; /* or */ SET #var_name := value;
both operators = and := are accepted
SELECT
SELECT col1, #var_name := col2 from tb_name WHERE "condition";
if multiple record sets found only the last value in col2 is kept (override);
SELECT col1, col2 INTO #var_name, col3 FROM ...
in this case the result of Select is not containing col2 values
Ex both methods used
-- TRIGGER_BEFORE_INSERT --- setting a column value from calculations
...
SELECT count(*) INTO #NR FROM a_table WHERE a_condition;
SET NEW.ord_col = IFNULL( #NR, 0 ) + 1;
...

Use set or select
SET #counter := 100;
SELECT #variable_name := value;
example :
SELECT #price := MAX(product.price)
FROM product

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;

Declare:
SET #a = 1;
Usage:
INSERT INTO `t` (`c`) VALUES (#a);

For any person using #variable in concat_ws function to get concatenated values, don't forget to reinitialize it with empty value. Otherwise it can use old value for same session.
Set #Ids = '';
select
#Ids := concat_ws(',',#Ids,tbl.Id),
tbl.Col1,
...
from mytable tbl;

I would like to give my awnswer here so people can try, solution for MySql that i think is easyer to understand:
set #countVal = (select count(*) from STATION);
/**
499/2 = 249,5 -> 250 -- ceil
499/2 = 249,5 + 1 = 250,5 -- floor 250
500/2 = 250 -- ceil 250
= 250 + 1 = 251 -- flor 251
**/
set #ceilVal = ceil(#countVal/2);
set #floorVal = floor( (#countVal/2) + 1);
SELECT ROUND(AVG( latitude ),4) FROM
(SELECT #lineNum:= #lineNum + 1 as id,
lat_n as latitude
FROM STATION s, ( SELECT #lineNum :=0 ) pivot
ORDER BY lat_n) as a
WHERE id IN ( #ceilVal, #floorVal );

SET Value
declare #Regione int;
set #Regione=(select id from users
where id=1) ;
select #Regione ;

Related

I am not able to determine the proper syntax for a DBeaver MySQL statement [duplicate]

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 * FROM places WHERE place BETWEEN start AND finish;
There are mainly three types of variables in MySQL:
User-defined variables (prefixed with #):
You can access any user-defined variable without declaring it or
initializing it. If you refer to a variable that has not been
initialized, it has a value of NULL and a type of string.
SELECT #var_any_var_name
You can initialize a variable using SET or SELECT statement:
SET #start = 1, #finish = 10;
or
SELECT #start := 1, #finish := 10;
SELECT * FROM places WHERE place BETWEEN #start AND #finish;
User variables can be assigned a value from a limited set of data
types: integer, decimal, floating-point, binary or nonbinary string,
or NULL value.
User-defined variables are session-specific. That is, a user
variable defined by one client cannot be seen or used by other
clients.
They can be used in SELECT queries using Advanced MySQL user variable techniques.
Local Variables (no prefix) :
Local variables needs to be declared using DECLARE before
accessing it.
They can be used as local variables and the input parameters
inside a stored procedure:
DELIMITER //
CREATE PROCEDURE sp_test(var1 INT)
BEGIN
DECLARE start INT unsigned DEFAULT 1;
DECLARE finish INT unsigned DEFAULT 10;
SELECT var1, start, finish;
SELECT * FROM places WHERE place BETWEEN start AND finish;
END; //
DELIMITER ;
CALL sp_test(5);
If the DEFAULT clause is missing, the initial value is NULL.
The scope of a local variable is the BEGIN ... END block within
which it is declared.
Server System Variables (prefixed with ##):
The MySQL server maintains many system variables configured to a default value.
They can be of type GLOBAL, SESSION or BOTH.
Global variables affect the overall operation of the server whereas session variables affect its operation for individual client connections.
To see the current values used by a running server, use the SHOW VARIABLES statement or SELECT ##var_name.
SHOW VARIABLES LIKE '%wait_timeout%';
SELECT ##sort_buffer_size;
They can be set at server startup using options on the command line or in an option file.
Most of them can be changed dynamically while the server is running using SET GLOBAL or SET SESSION:
-- Syntax to Set value to a Global variable:
SET GLOBAL sort_buffer_size=1000000;
SET ##global.sort_buffer_size=1000000;
-- Syntax to Set value to a Session variable:
SET sort_buffer_size=1000000;
SET SESSION sort_buffer_size=1000000;
SET ##sort_buffer_size=1000000;
SET ##local.sort_buffer_size=10000;
SET
SET #var_name = value; /* or */ SET #var_name := value;
both operators = and := are accepted
SELECT
SELECT col1, #var_name := col2 from tb_name WHERE "condition";
if multiple record sets found only the last value in col2 is kept (override);
SELECT col1, col2 INTO #var_name, col3 FROM ...
in this case the result of Select is not containing col2 values
Ex both methods used
-- TRIGGER_BEFORE_INSERT --- setting a column value from calculations
...
SELECT count(*) INTO #NR FROM a_table WHERE a_condition;
SET NEW.ord_col = IFNULL( #NR, 0 ) + 1;
...
Use set or select
SET #counter := 100;
SELECT #variable_name := value;
example :
SELECT #price := MAX(product.price)
FROM product
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;
Declare:
SET #a = 1;
Usage:
INSERT INTO `t` (`c`) VALUES (#a);
For any person using #variable in concat_ws function to get concatenated values, don't forget to reinitialize it with empty value. Otherwise it can use old value for same session.
Set #Ids = '';
select
#Ids := concat_ws(',',#Ids,tbl.Id),
tbl.Col1,
...
from mytable tbl;
I would like to give my awnswer here so people can try, solution for MySql that i think is easyer to understand:
set #countVal = (select count(*) from STATION);
/**
499/2 = 249,5 -> 250 -- ceil
499/2 = 249,5 + 1 = 250,5 -- floor 250
500/2 = 250 -- ceil 250
= 250 + 1 = 251 -- flor 251
**/
set #ceilVal = ceil(#countVal/2);
set #floorVal = floor( (#countVal/2) + 1);
SELECT ROUND(AVG( latitude ),4) FROM
(SELECT #lineNum:= #lineNum + 1 as id,
lat_n as latitude
FROM STATION s, ( SELECT #lineNum :=0 ) pivot
ORDER BY lat_n) as a
WHERE id IN ( #ceilVal, #floorVal );
SET Value
declare #Regione int;
set #Regione=(select id from users
where id=1) ;
select #Regione ;

MySQL use a variable as repeat value [duplicate]

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 * FROM places WHERE place BETWEEN start AND finish;
There are mainly three types of variables in MySQL:
User-defined variables (prefixed with #):
You can access any user-defined variable without declaring it or
initializing it. If you refer to a variable that has not been
initialized, it has a value of NULL and a type of string.
SELECT #var_any_var_name
You can initialize a variable using SET or SELECT statement:
SET #start = 1, #finish = 10;
or
SELECT #start := 1, #finish := 10;
SELECT * FROM places WHERE place BETWEEN #start AND #finish;
User variables can be assigned a value from a limited set of data
types: integer, decimal, floating-point, binary or nonbinary string,
or NULL value.
User-defined variables are session-specific. That is, a user
variable defined by one client cannot be seen or used by other
clients.
They can be used in SELECT queries using Advanced MySQL user variable techniques.
Local Variables (no prefix) :
Local variables needs to be declared using DECLARE before
accessing it.
They can be used as local variables and the input parameters
inside a stored procedure:
DELIMITER //
CREATE PROCEDURE sp_test(var1 INT)
BEGIN
DECLARE start INT unsigned DEFAULT 1;
DECLARE finish INT unsigned DEFAULT 10;
SELECT var1, start, finish;
SELECT * FROM places WHERE place BETWEEN start AND finish;
END; //
DELIMITER ;
CALL sp_test(5);
If the DEFAULT clause is missing, the initial value is NULL.
The scope of a local variable is the BEGIN ... END block within
which it is declared.
Server System Variables (prefixed with ##):
The MySQL server maintains many system variables configured to a default value.
They can be of type GLOBAL, SESSION or BOTH.
Global variables affect the overall operation of the server whereas session variables affect its operation for individual client connections.
To see the current values used by a running server, use the SHOW VARIABLES statement or SELECT ##var_name.
SHOW VARIABLES LIKE '%wait_timeout%';
SELECT ##sort_buffer_size;
They can be set at server startup using options on the command line or in an option file.
Most of them can be changed dynamically while the server is running using SET GLOBAL or SET SESSION:
-- Syntax to Set value to a Global variable:
SET GLOBAL sort_buffer_size=1000000;
SET ##global.sort_buffer_size=1000000;
-- Syntax to Set value to a Session variable:
SET sort_buffer_size=1000000;
SET SESSION sort_buffer_size=1000000;
SET ##sort_buffer_size=1000000;
SET ##local.sort_buffer_size=10000;
SET
SET #var_name = value; /* or */ SET #var_name := value;
both operators = and := are accepted
SELECT
SELECT col1, #var_name := col2 from tb_name WHERE "condition";
if multiple record sets found only the last value in col2 is kept (override);
SELECT col1, col2 INTO #var_name, col3 FROM ...
in this case the result of Select is not containing col2 values
Ex both methods used
-- TRIGGER_BEFORE_INSERT --- setting a column value from calculations
...
SELECT count(*) INTO #NR FROM a_table WHERE a_condition;
SET NEW.ord_col = IFNULL( #NR, 0 ) + 1;
...
Use set or select
SET #counter := 100;
SELECT #variable_name := value;
example :
SELECT #price := MAX(product.price)
FROM product
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;
Declare:
SET #a = 1;
Usage:
INSERT INTO `t` (`c`) VALUES (#a);
For any person using #variable in concat_ws function to get concatenated values, don't forget to reinitialize it with empty value. Otherwise it can use old value for same session.
Set #Ids = '';
select
#Ids := concat_ws(',',#Ids,tbl.Id),
tbl.Col1,
...
from mytable tbl;
I would like to give my awnswer here so people can try, solution for MySql that i think is easyer to understand:
set #countVal = (select count(*) from STATION);
/**
499/2 = 249,5 -> 250 -- ceil
499/2 = 249,5 + 1 = 250,5 -- floor 250
500/2 = 250 -- ceil 250
= 250 + 1 = 251 -- flor 251
**/
set #ceilVal = ceil(#countVal/2);
set #floorVal = floor( (#countVal/2) + 1);
SELECT ROUND(AVG( latitude ),4) FROM
(SELECT #lineNum:= #lineNum + 1 as id,
lat_n as latitude
FROM STATION s, ( SELECT #lineNum :=0 ) pivot
ORDER BY lat_n) as a
WHERE id IN ( #ceilVal, #floorVal );
SET Value
declare #Regione int;
set #Regione=(select id from users
where id=1) ;
select #Regione ;

Multiple Variable If Statement

I have recently been able to produce a procedure where if a variable is not set I can set it to null. Now I am now looking to have multiple variables, but if a value has not been set to that variable, for it then to return all rows.
BEGIN
DECLARE ps_Project_Leader VARCHAR(15);
DECLARE ps_RD_Plan VARCHAR (15);
DECLARE ps_Approval_Status VARCHAR (15);
DECLARE ps_Design_Plan VARCHAR (15);
SET ps_Project_Leader = ifnull(Project_Leader,null);
SET ps_RD_Plan = ifnull(RD_Plan,null);
SET ps_Approval_Status = ifnull(Approval_Status,null);
SET ps_Design_Plan = ifnull(Design_Plan,null);
SELECT pp.pid,
pp.description,
pp.approval_status,
pp.design_plan,
pp.rd_plan,
pp.estimated_completion,
pp.project_leader,
pp.actual_completion
FROM project_register pp
WHERE pp.project_leader =Project_Leader
OR Project_Leader is null
and pp.rd_plan =RD_Plan
OR RD_Plan is null
and pp.approval_status = Approval_Status
OR Approval_Status is null
and pp.design_plan = Design_Plan
OR Design_Plan is null
and
PP.actual_completion is null;
end
For instance if i have set 2 of the variables and not the other 2, I do not want it to search on the variables that have not been set.
Many Thanks in advance, if i have not made complete sense (i am new to this so i appologies) I will be happy to clear things up.
You need to parenthesize your WHERE expression correctly:
WHERE (pp.project_leader = ps_Project_Leader
OR ps_Project_Leader is null)
and (pp.rd_plan = ps_RD_Plan
OR ps_RD_Plan is null)
and (pp.approval_status = ps_Approval_Status
OR ps_Approval_Status is null)
and (pp.design_plan = ps_Design_Plan
OR ps_Design_Plan is null)
and PP.actual_completion is null;
because AND has higher precedence than OR.
You aren't referencing the local variables, only the procedure arguments. (It doesn't look like you actually need local variables.)
I prefer to use parens around the AND and OR predicates, even if they aren't required. I never have to lookup if AND or OR takes precedence when I use parens, because it doesn't matter, because I'm always specifying the precedence.
I'd help the reader out, and format my SQL like this:
WHERE ( pp.project_leader = Project_Leader OR Project_Leader IS NULL )
AND ( pp.rd_plan = RD_Plan OR RD_Plan IS NULL )
AND ( pp.approval_status = Approval_Status OR Approval_Status IS NULL )
AND ( pp.design_plan = Design_Plan OR Design_Plan IS NULL )
That way, each line is a "check" of a single column, which is either enabled (with a non-NULL value) or disabled with NULL value.
Really just personal preference, I just find it easier to read that way, even if the line is a little bit longer, I'd rather have the check all one one line.
Again, the local variables aren't needed.
But, you could just set local variables equal to the parameter values, and then reference the local variables in your SQL statement. That really helps out when a variable has the same name as a column, because if the are named the same, MySQL is going to assume it's a reference to column name rather than a variable name. Using a local variable gives you a chance to rename it so it won't be confused with a column name.
UPDATE
I just noticed that the parameter variables names ARE the same as the column names, and that's going to be a problem.
You want your variable names to be DIFFERENT than the column names. You want to make sure that the datatypes of the variables match the columns... later, when you change a column from VARCHAR(15) to VARCHAR(30), you'll need to revisit the procedure and change the definitions of the procedure arguments as well as the local variables.
BEGIN
-- local variable names are DISTINCT from any column name
-- in any table referenced by a query these are used in
DECLARE ps_Project_Leader VARCHAR(15);
DECLARE ps_RD_Plan VARCHAR(15);
...
-- copy parameter values to local variables
SET ps_Project_Leader = Project_Leader ;
SET ps_RD_Plan = RD_Plan ;
...
-- query references local variable names
...
WHERE ( pp.project_leader = ps_Project_Leader OR ps_Project_Leader IS NULL )
AND ( pp.rd_plan = ps_RD_Plan OR ps_RD_Plan IS NULL )
...

How to declare a variable in MySQL?

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 * FROM places WHERE place BETWEEN start AND finish;
There are mainly three types of variables in MySQL:
User-defined variables (prefixed with #):
You can access any user-defined variable without declaring it or
initializing it. If you refer to a variable that has not been
initialized, it has a value of NULL and a type of string.
SELECT #var_any_var_name
You can initialize a variable using SET or SELECT statement:
SET #start = 1, #finish = 10;
or
SELECT #start := 1, #finish := 10;
SELECT * FROM places WHERE place BETWEEN #start AND #finish;
User variables can be assigned a value from a limited set of data
types: integer, decimal, floating-point, binary or nonbinary string,
or NULL value.
User-defined variables are session-specific. That is, a user
variable defined by one client cannot be seen or used by other
clients.
They can be used in SELECT queries using Advanced MySQL user variable techniques.
Local Variables (no prefix) :
Local variables needs to be declared using DECLARE before
accessing it.
They can be used as local variables and the input parameters
inside a stored procedure:
DELIMITER //
CREATE PROCEDURE sp_test(var1 INT)
BEGIN
DECLARE start INT unsigned DEFAULT 1;
DECLARE finish INT unsigned DEFAULT 10;
SELECT var1, start, finish;
SELECT * FROM places WHERE place BETWEEN start AND finish;
END; //
DELIMITER ;
CALL sp_test(5);
If the DEFAULT clause is missing, the initial value is NULL.
The scope of a local variable is the BEGIN ... END block within
which it is declared.
Server System Variables (prefixed with ##):
The MySQL server maintains many system variables configured to a default value.
They can be of type GLOBAL, SESSION or BOTH.
Global variables affect the overall operation of the server whereas session variables affect its operation for individual client connections.
To see the current values used by a running server, use the SHOW VARIABLES statement or SELECT ##var_name.
SHOW VARIABLES LIKE '%wait_timeout%';
SELECT ##sort_buffer_size;
They can be set at server startup using options on the command line or in an option file.
Most of them can be changed dynamically while the server is running using SET GLOBAL or SET SESSION:
-- Syntax to Set value to a Global variable:
SET GLOBAL sort_buffer_size=1000000;
SET ##global.sort_buffer_size=1000000;
-- Syntax to Set value to a Session variable:
SET sort_buffer_size=1000000;
SET SESSION sort_buffer_size=1000000;
SET ##sort_buffer_size=1000000;
SET ##local.sort_buffer_size=10000;
SET
SET #var_name = value; /* or */ SET #var_name := value;
both operators = and := are accepted
SELECT
SELECT col1, #var_name := col2 from tb_name WHERE "condition";
if multiple record sets found only the last value in col2 is kept (override);
SELECT col1, col2 INTO #var_name, col3 FROM ...
in this case the result of Select is not containing col2 values
Ex both methods used
-- TRIGGER_BEFORE_INSERT --- setting a column value from calculations
...
SELECT count(*) INTO #NR FROM a_table WHERE a_condition;
SET NEW.ord_col = IFNULL( #NR, 0 ) + 1;
...
Use set or select
SET #counter := 100;
SELECT #variable_name := value;
example :
SELECT #price := MAX(product.price)
FROM product
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;
Declare:
SET #a = 1;
Usage:
INSERT INTO `t` (`c`) VALUES (#a);
For any person using #variable in concat_ws function to get concatenated values, don't forget to reinitialize it with empty value. Otherwise it can use old value for same session.
Set #Ids = '';
select
#Ids := concat_ws(',',#Ids,tbl.Id),
tbl.Col1,
...
from mytable tbl;
I would like to give my awnswer here so people can try, solution for MySql that i think is easyer to understand:
set #countVal = (select count(*) from STATION);
/**
499/2 = 249,5 -> 250 -- ceil
499/2 = 249,5 + 1 = 250,5 -- floor 250
500/2 = 250 -- ceil 250
= 250 + 1 = 251 -- flor 251
**/
set #ceilVal = ceil(#countVal/2);
set #floorVal = floor( (#countVal/2) + 1);
SELECT ROUND(AVG( latitude ),4) FROM
(SELECT #lineNum:= #lineNum + 1 as id,
lat_n as latitude
FROM STATION s, ( SELECT #lineNum :=0 ) pivot
ORDER BY lat_n) as a
WHERE id IN ( #ceilVal, #floorVal );
SET Value
declare #Regione int;
set #Regione=(select id from users
where id=1) ;
select #Regione ;

Using variable in a LIMIT clause in MySQL

I am writing a stored procedure where I have an input parameter called my_size that is an INTEGER. I want to be able to use it in a LIMIT clause in a SELECT statement. Apparently this is not supported, is there a way to work around this?
# I want something like:
SELECT * FROM some_table LIMIT my_size;
# Instead of hardcoding a permanent limit:
SELECT * FROM some_table LIMIT 100;
For those, who cannot use MySQL 5.5.6+ and don't want to write a stored procedure, there is another variant. We can add where clause on a subselect with ROWNUM.
SET #limit = 10;
SELECT * FROM (
SELECT instances.*,
#rownum := #rownum + 1 AS rank
FROM instances,
(SELECT #rownum := 0) r
) d WHERE rank < #limit;
STORED PROCEDURE
DELIMITER $
CREATE PROCEDURE get_users(page_from INT, page_size INT)
BEGIN
SET #_page_from = page_from;
SET #_page_size = page_size;
PREPARE stmt FROM "select u.user_id, u.firstname, u.lastname from users u limit ?, ?;";
EXECUTE stmt USING #_page_from, #_page_size;
DEALLOCATE PREPARE stmt;
END$
DELIMITER ;
USAGE
In the following example it retrieves 10 records each time by providing start as 1 and 11. 1 and 11 could be your page number received as GET/POST parameter from pagination.
call get_users(1, 10);
call get_users(11, 10);
A search turned up this article. I've pasted the relevant text below.
Here's a forum post showing an example of prepared statements letting
you assign a variable value to the limit clause:
http://forums.mysql.com/read.php?98,126379,133966#msg-133966
However, I think this bug should get some attention because I can't
imagine that prepared statements within a procedure will allow for any
procedure-compile-time optimizations. I have a feeling that prepared
statements are compiled and executed at the runtime of the procedure,
which probaby has a negative impact on efficiency. If the limit
clause could accept normal procedure variables (say, a procedure
argument), then the database could still perform compile-time
optimizations on the rest of the query, within the procedure. This
would likely yield faster execution of the procedure. I'm no expert
though.
I know this answer has come late, but try SQL_SELECT_LIMIT.
Example:
Declare rowCount int;
Set rowCount = 100;
Set SQL_SELECT_LIMIT = rowCount;
Select blah blah
Set SQL_SELECT_LIMIT = Default;
This feature has been added to MySQL 5.5.6.
Check this link out.
I've upgraded to MySQL 5.5 just for this feature and works great.
5.5 also has a lot of performance upgrades in place and I totally recommend it.
Another way, the same as wrote "Pradeep Sanjaya", but using CONCAT:
CREATE PROCEDURE `some_func`(startIndex INT, countNum INT)
READS SQL DATA
COMMENT 'example'
BEGIN
SET #asd = CONCAT('SELECT `id` FROM `table` LIMIT ',startIndex,',',countNum);
PREPARE zxc FROM #asd;
EXECUTE zxc;
END;
As of MySQL version 5.5.6, you can specify LIMIT and OFFSET with variables / parameters.
For reference, see the 5.5 Manual, the 5.6 Manual and #Quassnoi's answer
I've faced the same problem using MySql 5.0 and wrote a procedure with the help of #ENargit's answer:
CREATE PROCEDURE SOME_PROCEDURE_NAME(IN _length INT, IN _start INT)
BEGIN
SET _start = (SELECT COALESCE(_start, 0));
SET _length = (SELECT COALESCE(_length, 999999)); -- USING ~0 GIVES OUT OF RANGE ERROR
SET #row_num_personalized_variable = 0;
SELECT
*,
#row_num_personalized_variable AS records_total
FROM(
SELECT
*,
(#row_num_personalized_variable := #row_num_personalized_variable + 1) AS row_num
FROM some_table
) tb
WHERE row_num > _start AND row_num <= (_start + _length);
END;
Also included the total rows obtained by the query with records_total.
you must DECLARE a variable and after that set it. then the LIMIt will work and put it in a StoredProcedure not sure if it works in normal query
like this:
DECLARE rowsNr INT DEFAULT 0;
SET rowsNr = 15;
SELECT * FROM Table WHERE ... LIMIT rowsNr;