calling stored procedure is giving an error - mysql

The error mysql is throwing is
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
My using phpmyadmin to wreite procedures.
and my stored procedure is
BEGIN
DECLARE page_limit int(100);
DECLARE page_no VARCHAR(100);
DECLARE rstarts int(100) DEFAULT 1;
DECLARE rends int(100) DEFAULT 15;
DECLARE query varchar(255) ;
set query = ' select brandid from brandinfo limit #rstarts,#rends';
PREPARE stmt FROM #query;
set rstarts = 15;
set rends =1;
EXECUTE stmt using #rstarts,#rends;
DEALLOCATE PREPARE stmt;
END

Declared variables and variables beginning with # are two different stories. Read about user defined variables (the ones with #).
DELIMITER $$
CREATE PROCEDURE your_procedure_name()
BEGIN
SET #rstarts = 1;
SET #rends = 15;
set #query = 'select brandid from brandinfo limit ?, ?';
PREPARE stmt FROM #query;
EXECUTE stmt using #rstarts, #rends;
DEALLOCATE PREPARE stmt;
END $$
DELIMITER ;
Also in your query string you want to use ? as parameters, not the variable names. And you might miss on setting the delimiter to something different than ;

Related

Execute sql using a stored procedure in mysql

I have the following stored procedure. The idea is to get a list of databases and execute an sql statement.
DELIMITER $$
CREATE PROCEDURE updateMySQL (
IN theSQL varchar(4000)
)
BEGIN
DECLARE finished INTEGER DEFAULT 0;
DECLARE theDatabases varchar(100) DEFAULT "";
-- declare cursor for employee email
DEClARE curDatabase
CURSOR FOR
SELECT schema_name FROM information_schema.schemata where SCHEMA_NAME = 'mydb' order by 1;
-- declare NOT FOUND handler
DECLARE CONTINUE HANDLER
FOR NOT FOUND SET finished = 1;
OPEN curDatabase;
getDatabase: LOOP
FETCH curDatabase INTO theDatabases;
IF finished = 1 THEN
LEAVE getDatabase;
END IF;
-- build email list
-- SET emailList = CONCAT(theDatabases,";",emailList);
SET #sql:=CONCAT('USE ',#curDatabase);
PREPARE dynamic_statement FROM #SQL;
EXECUTE dynamic_statement;
PREPARE dynamic_statement FROM #theSQL;
EXECUTE dynamic_statement;
END LOOP getDatabase;
CLOSE curDatabase;
END$$
DELIMITER ;
I am attempting to execute the stored procedure like this,
SET #theSQL = 'ALTER VIEW `Reports` AS
SELECT DISTINCT
`tableA`.`Id` AS `Id`,
`tableA`.`letterId` AS `letterId`
FROM
`mytable` `tableA`
ORDER BY 1';
call updateMySQL(#theSQL);
EDIT There was an error on executing the procedure,
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 'NULL' at line 1
I am using mysql 8.0.17
Investigate carefully MySQL 8.0 Reference Manual / SQL Statements / Prepared Statements, the section "SQL Syntax Allowed in Prepared Statements".
This section claims FULL list of statements which are allowed in Prepared statements. ALTER VIEW is NOT listed. So it is NOT allowed.
Use DROP VIEW and CREATE VIEW instead.
Always receive and investigate all error messages.
You should change this part
SET #sql:=CONCAT('USE ',#curDatabase);
PREPARE dynamic_statement FROM #SQL;
EXECUTE dynamic_statement;
PREPARE dynamic_statement FROM #theSQL;
EXECUTE dynamic_statement;
to this:
SET #sql:=CONCAT('USE ',#curDatabase);
PREPARE dynamic_statement FROM #SQL;
EXECUTE dynamic_statement;
DEALLOCATE PREPARE dynamic_statement; /* don't forget to deallocate */
/* there's a difference between the variables #theSQL and theSQL (your parameter) */
/* IIRC prepare statements need user defined variables or a syntax error occurs. Therefore I simply assign the parameter to a user-defined variable */
SET #theSQL = theSQL;
PREPARE dynamic_statement FROM #theSQL;
EXECUTE dynamic_statement;
DEALLOCATE PREPARE dynamic_statement;
Read more about user-defined variables here: https://dev.mysql.com/doc/refman/8.0/en/user-variables.html
Here the differences are explained: https://stackoverflow.com/a/1010042/447489
When you don't initialize them, their content is just NULL. Since there's a difference between user-defined variables and local variables (and also your parameter variable), your current solution did nothing.

MYSQL - Execute procedure to execute statement from table

I am working in a stored procedure that is fetching queries from a table and execute them.
The problem is that I have some queries with single/doubled quotes and it is throwing an error on execute them.
Procedure
delimiter $$
drop procedure if exists run_change_ids_queries$$
create procedure run_change_ids_queries()
begin
declare s_query TEXT;
declare done bool default false;
declare c_queries cursor for
select `query` from `queries` WHERE `executed` = 0 ORDER BY `qry_id` ASC;
declare continue handler for not found set done = true;
open c_queries;
read_loop: loop
fetch c_queries into s_query;
if done then
leave read_loop;
end if;
-- run the query
set #sql = s_query;
prepare stmt from #sql;
execute stmt;
deallocate prepare stmt;
-- update executed flag on query
set #update = CONCAT('UPDATE `queries` SET `executed` = 1 WHERE `query` LIKE \'',#sql,'\';');
prepare stmt from #update;
execute stmt;
deallocate prepare stmt;
end loop;
end$$
Query update urisegments as s inner join change_product_ids as p on concat('{"product_id":"', p.old_id, '"}') = s.primary_key_value set s.primary_key_value = CONCAT('{"product_id":', p.new_id, '"}') where s.app_namespace = 'Shop' and s.primary_key_value like '%product_id%'; is throwing error: [42000][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 '{"product_id":"', p.old_id, '"}') = s.primary_key_value set s.primary_key_value ' at line 1
Workaround #01
I already tried to escape single/doubled quotes into \' and \" respectively, but it throws another error:
[42000][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 '\'{\"product_id\":\"\', p.old_id, \'\"}\') = s.primary_key_value set s.primary_k' at line 1.
Don't try to concatenate the query into the SQL. Prepared statements can contain placeholders, which you fill in when you use the EXECUTE statement.
set #update = 'UPDATE `queries` SET `executed` = 1 WHERE `query` = ?');
prepare stmt from #update;
execute stmt USING #sql;
The statement is not escaped.
All single/doubled quotes should be escaped.
update urisegments as s
inner join change_product_ids as p on concat(\'{\"product_id\":\"\', p.old_id, \'\"}\') = s.primary_key_value
set s.primary_key_value = CONCAT(\'{\"product_id\":\', p.new_id, \'\"}\')
where s.app_namespace = \'Shop\' and s.primary_key_value like \'%product_id%\';
Instead of testing for the query, test for its id:
... WHERE qry_id = ?
(Add that column to the initial SELECT.)

Dynamic query execute in MySQL

I'm trying to generate a dynamic SQL command stored in a LongText that will be executed in a stored procedure.
The code for the stored procedure looks like this:
DROP PROCEDURE IF EXISTS test.Dquery()
DELIMITER //
CREATE PROCEDURE test.Dquery()
BEGIN
DECLARE EXEC LONGTEXT DEFAULT '';
SET EXEC = CONCAT(
'
SELECT * FROM test.customers LIMIT 5;
');
PREPARE stmt FROM #EXEC;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END //
DELIMITER ;
Getting an error in execution... Any ideas?

Error in Converting SQL Server stored procedure to Mysql

I am trying to convert a SQL Server stored procedure to Mysql as I am migrating an entire database to Mysql
But I am not able to convert a few of the stored procedures which are using XML interaction. I am not a Mysql guy. So could some one please help me out?
Thanks in advance.
My stored procedure in SQL Server looks like this:
ALTER PROCEDURE [dbo].[usp_MemberToDoList_UpdateForMember]
(
#xml nvarchar(max),
#login varchar(255)
)
AS
BEGIN
SET NOCOUNT ON;
DECLARE #doc int;
DECLARE #now datetime = GETUTCDATE();
EXEC [sp_xml_preparedocument] #doc OUTPUT, #xml;
UPDATE
[mtdl]
SET
[taskCompleteDate] = CASE WHEN [isCompleted] = CONVERT(bit, 1) THEN #now ELSE NULL END,
[updatedBy] = #login,
[dateUpdated] = GETUTCDATE()
FROM
[MemberToDoList] [mtdl]
JOIN
OPENXML (#doc, '/todos/todo') WITH
(
[id] int,
[isCompleted] bit
) [x] ON [x].[id] = [mtdl].[memberToDoListId];
EXEC [sp_xml_removedocument] #doc;
END
When I convert to Mysql it looks like
CREATE PROCEDURE `conversion`.`usp_MemberToDoList_UpdateForMember` (xml longtext,
login varchar(255))
BEGIN
DECLARE v_doc int;
DECLARE v_now datetime(3);
set v_now = UTC_TIMESTAMP();
CALL sp_xml_preparedocument(#doc)
PREPARE stmt FROM #stmt_str;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
v_doc OUT, xml;
UPDATE
mtdl
SET
`taskCompleteDate` = CASE WHEN `isCompleted` = CONVERT(1,UNSIGNED) THEN v_now ELSE NULL END
,`updatedBy` = #login,
`dateUpdated` = UTC_TIMESTAMP()
FROM
`MemberToDoList` `mtdl`
JOIN
ExtractValue(#doc, '/todos/todo') WITH
(
`id` int,
`isCompleted` bit
) `x` ON [x].[id] = `mtdl`.`memberToDoListId`;
SET #stmt_str = `sxml_removedocument`;
PREPARE stmt FROM #stmt_str;
EXECUTE stmt;`enter code here`
DEALLOCATE PREPARE stmt; #doc;
END
but keeps me giving error:
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 'END' at line 1
FYI I am using Mysql version 5.6
try this:
your creating nor sql query, if you wants to create the sql procedure you should must add the delimiter in the starting and ending in your query. And ; add the like my query END; as query is following as:
delimiter //
CREATE PROCEDURE `conversion`.`usp_MemberToDoList_UpdateForMember` (xml longtext,
login varchar(255))
BEGIN
DECLARE v_doc int;
DECLARE v_now datetime(3);
set v_now = UTC_TIMESTAMP();
CALL sp_xml_preparedocument(#doc)
PREPARE stmt FROM #stmt_str;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
v_doc OUT, xml;
UPDATE
mtdl
SET
`taskCompleteDate` = CASE WHEN `isCompleted` = CONVERT(1,UNSIGNED) THEN v_now ELSE NULL END
,`updatedBy` = #login,
`dateUpdated` = UTC_TIMESTAMP()
FROM
`MemberToDoList` `mtdl`
JOIN
ExtractValue(#doc, '/todos/todo') WITH
(
`id` int,
`isCompleted` bit
) `x` ON [x].[id] = `mtdl`.`memberToDoListId`;
SET #stmt_str = `sxml_removedocument`;
PREPARE stmt FROM #stmt_str;
EXECUTE stmt;`enter code here`
DEALLOCATE PREPARE stmt; #doc;
END; //
delimiter ;
http://dev.mysql.com/doc/refman/5.0/en/create-procedure.html

A loop for adding multiple columns into a table in mysql

The purpose of the following loop is to create 10 columns and name them as'col_20','col_21'...
.This loop could be created but a syntax error occurred when I tried to run it.
This is what got after I called MYLOOP() in Mysql
"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"
DELIMITER $$
CREATE PROCEDURE MYLOOP()
BEGIN
DECLARE i int;
DECLARE str varchar(255);
SET i = 20;
WHILE i < 30 DO
SET str = CONCAT('col_',i);
SET #sql = 'ALTER TABLE TEST ADD '+ str + ' INT;';
SET i = i + 1;
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END WHILE;
END $$
DELIMITER ;
CALL MYLOOP();