Using variable in select query - mysql

I am trying get count value from a table and storing it in a variable using select statement in stored procedure. But when I use following lines of statemnts
DECLARE totalRegister INTEGER;
SET #sqlstmt = CONCAT('SELECT COUNT(DISTINCT(msisdn)) INTO ', totalRegister, ' FROM sm_history.svc_mgmt_', #yesterdayMonth,' WHERE action_type = 1 AND DATE(created) = ', yesterday);
PREPARE statement FROM #sqlstmt;
EXECUTE statement;
DEALLOCATE PREPARE statement;
I get following error on calling the stored procedure
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 'NULL' at line 1
I further debugged my stored procedure by using Select #sql; and surprised to see it was returning NULL
Edit 1: Variables yesterday and yesterdayDate are returning values correctly so I am sure there is no issue with these variables. The problem is due to totalRegister variable

Luckily I got solution by using hit and trial. Instead of using totalRegister as variable in the CONCAT function replaced it with #totalRegister which caused the stored procedure to work fine.
DECLARE totalRegister INTEGER;
SET #sqlstmt = CONCAT('SELECT COUNT(DISTINCT(msisdn)) INTO #totalRegister FROM sm_history.svc_mgmt_',#yesterdayMonth ,' WHERE action_type = 1 AND DATE(created) = ', "'", yesterday, "'");
PREPARE statement FROM #sqlstmt;
EXECUTE statement;
DEALLOCATE PREPARE statement;
select #totalRegister;
Above thing worked fine. Anyways thanks to all for contribution

Related

allocated prepared query error syntax error

I try to execute a variable query within a custom mysql function, here's the script :
DELIMITER $
CREATE FUNCTION is_present(in_id BIGINT, in_table_name VARCHAR(255)) RETURNS BIT
BEGIN
DECLARE stm VARCHAR(255);
DECLARE result BIT DEFAULT 0;
SET stm := CONCAT('SELECT IF(COUNT(*), 1, 0) INTO result FROM', in_table_name, 'WHERE id=? LIMIT 1');
PREPARE query FROM stm;
EXECUTE query USING in_id;
DEALLOCATE PREPARE query;
RETURN result;
END $
DELIMITER ;
Mysql warns me about the syntax :
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 'stm; EXECUTE query USING in_id; DEALLOCATE PREPARE query;
RETURN result; ' at line 9
I think you are missing a semicolon before var name:
PREPARE query FROM :stm;

MySQL SQL syntax error near '0' at line 1

I have tried various modifications to make this work but I can't seem to remove the error. My SQLQuery string is much larger than the one below but same set up. I tried using a CONCAT(' ') statement but had issues. So I tried using this format but still receive the same error. any suggestions?
CREATE DEFINER=`root`#`%` PROCEDURE `stp_Select_GetTbl`(IN strWhereClause
VARCHAR(255))
BEGIN
DECLARE SQLQuery varchar(1000);
SET SQLQuery = '
SELECT `Part Num` AS `PPNumber`,
`Shop Num` as `SOrder`
FROM `track`.`s list` WHERE ';
SET #SQLQuery = #SQLQuery + strWhereClause + '';
PREPARE stmt FROM #SQLQuery;
EXECUTE stmt;
END
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 '0' at line 1
`
I have tried not declaring SQLQuery... changing varchar size... reorganizing and even using the example below
SET #getList =
CONCAT('SELECT (t1, t2, t3) FROM (SELECT t1, t2, t3) as mainSelect WHERE ', strWhereClause, '');
PREPARE stmt FROM #getList;
EXECUTE stmt;
END
but get error at
.... MySQL server version for the right syntax to use near '0
I need to define a string for my SELECT statement because I create the WHERE clause in my stored procedure.

MySQL Stored Procedure with Prepared Statement does not work

I have the following stored procedure:
CREATE PROCEDURE getLastValueAutomaticShelter(IN fieldName varchar(30), position_number INT)
BEGIN
SET #query = CONCAT('SELECT * FROM automatic_changes WHERE',fieldName,'IS NOT NULL AND P_id=?');
PREPARE stmt FROM #query;
SET #position_number=position_number;
EXECUTE stmt USING #position_number;
DEALLOCATE PREPARE stmt;
END
Then I am running it:
mysql> call getLastValueAutomaticShelter('current_level', 500)//
And getting the following error:
ERROR 1064 (42000): 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 'NOT N
ULL AND P_id=?' at line 1
Any ideas? Thanks.
You need to add some spaces in there:
SET #query = CONCAT('SELECT * FROM automatic_changes WHERE ',fieldName,' IS NOT NULL AND P_id=?');
/* right ^ here....and ^ here*/
Otherwise your final query might look like this:
SELECT * FROM automatic_changes WHEREcolumnameIS NOT NULL AND P_id='whatever';
You get the idea :)

SQL : Running select statement for local string variable

Here is a case where I am running SQL select statement on local string.
If I run normal select query for my tables then it works.
select * from tablesname
But if I have following case :
declare #string nvarchar(400)
set #string = N'from tablesname'
Now if I run select * from #string , it is not working as expected.
Please suggest me for to resolve this problem, since I want to run the select statement in this way only.
If I should try some other way, then suggest me that.
Thanks,
Tausif.
Assuming you are using MySQL since your question is tagged with it, although this set #string = N'from tablesname' suggests, that you're using MS SQL Server or something:
SET #yourDynamicTablename = 'yourTable';
SET #sql = CONCAT('SELECT * FROM ', #yourDynamicTablename );
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
You might want to put that in a stored procedure.
Your attempt wasn't working, because you can't select from a string. For further reading about prepared statements, which are also useful for avoiding SQL injection attacks, have a look in the manual.

syntax error with concat and limit in mysql

I am getting syntax error on runnning this. Is it possible to use variables with limit without using concat function?
CREATE PROCEDURE SP(_start INT,_end INT)
BEGIN
DECLARE _qry VARCHAR(500) DEFAULT CONCAT('select * from tbl limit ',_start,_end);
PREPARE stmt FROM _qry;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
Error is
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 '_qry;
EXECUTE stmt;
You missed , before the offset.
CREATE PROCEDURE SP(_start INT,_end INT)
BEGIN
DECLARE _qry VARCHAR(500) DEFAULT CONCAT('select * from tbl limit ', _start, ',', _end);
PREPARE stmt FROM _qry;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
I think you have to change the DEFAULT DELIMITER first and adding PARAMETER DIRECTION before creating the STORED PROCEDURE.
There are good reasons to use prepared statements:
1. ) Save on query parsing
2.) Save on data conversion and copying
3.) Avoid SQL Injection
4.) Save memory on handling blobs
There are also drawbacks and chewats of using prepared statements:
1.) Query cache does not work
2.) Extra server round trip required if statement used only once
3.) Not all statements can be prepared. So you can’t use prepared API
exclusively you’ll need to fall back to normal API for some statements
4.) Newer and sometimes buggy code. I had a lot of problems with PHP
prepared statements. It is getting better but still it is less mature
than standard API
5.) You can’t use placeholders in place of all identifiers. For example you
can’t use them for table name. In certain version it even does not work for
LIMIT boundaries
6.) Inconvenient list handling. Unlike in for example PEAR emulated prepard
statements there is no nice way to pass list of values to IN
7.) Harder tracing. Logs were now fixed to include full statement text not
only “Execute” but in SHOW INNODB STATUS you would still see statements
without actual values – quite inonvenient for analyses.
try this one:
UPDATE 1
DELIMITER $$
CREATE PROCEDURE SP(IN _start INT,IN _end INT)
BEGIN
SET #iQuery = CONCAT('select * from tbl limit ', _start, ',', _end);
PREPARE stmt FROM #iQuery;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END $$
DELIMITER ;
MySQL Syntax for Prepared Statements
delimiter //
drop procedure if exists SP //
create procedure SP(_start int,_end int)
begin
declare _qry varchar(500);
set #_qry = 'select * from tbl limit ?, ?';
set #start = _start;
set #end = _end;
prepare stmt from #qry;
execute stmt using #start, #end;
deallocate prepare stmt;
end; //
delimiter ;
call SP(1,2);