Mysql Stored Proc Passing String List - mysql

I have this Stored Procedure below, it works if my PostId is Integer field
and i send postIdList as a comma separated string '1,2,3,4'...
But if I change my PostId to GUID(char(36) it does not work for me.
it gives me an syntax error saying
"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 '"2d9d3ebc-6c9f-467a-8181-8a38891756b)' at line 1"
CREATE DEFINER=`root`#`%` PROCEDURE `GetComments`(
IN postIdList TEXT
)
BEGIN
set #sql = CONCAT('select * from PostComment where PostId in (', postIdList, ') ');
PREPARE q FROM #sql;
execute q;
END$$
this is how i am calling it
CAll GetComments(
'fff78ee0-396b-4300-952b-eee72d65261a,fff517dc-a7b7-441e-85bb-b5134828c0c9');
Any Ideas how to resolve this?

Your ids are not integers. You need to pass them in with single quotes or do something like this:
set #sql = CONCAT('select * from PostComment where PostId in (''',
replace(postIdList, ',', ''','''),
''') ');
That is, replace each comma with a single quote, comma, single quote. And then put quotes at the beginning and end of the list.

Related

cannot insert datetime field with stored procedure into mysql database

I am getting this syntax error when trying to insert a datetime into mysql database.
pymysql.err.ProgrammingError: (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 '00:00:01)' at line 1")
I am using pymysql and flask-mysql. This is my code:
cursor.execute("""DROP TABLE IF EXISTS test_table_2;""")
cursor.execute("""DROP PROCEDURE IF EXISTS updateTestProc2;""")
testTable = """CREATE TABLE IF NOT EXISTS test_table_2 (
time DATETIME,
PRIMARY KEY (time)
);
"""
testProc = """
CREATE PROCEDURE updateTestProc2(
IN ptime DATETIME
)
BEGIN
SET #queryStr = CONCAT('INSERT INTO test_table_2(time) VALUES ( ',
ptime,
')
;'
);
PREPARE query FROM #queryStr;
EXECUTE query;
DEALLOCATE PREPARE query;
END
"""
cursor.execute(testTable)
cursor.execute(testProc)
proc_input = ('1990-05-23 00:00:01',)
cursor.callproc('updateTestProc2', proc_input)
Do not use string concatenation to get values into statement. That's error prone and might make your program vulnerable to SQL injection attacks. Use parameters. Change your procedure's code to:
...
SET #queryStr = 'INSERT INTO test_table_2 (time) VALUES (?)';
PREPARE query FROM #queryStr;
EXECUTE query USING ptime;
DEALLOCATE PREPARE query;
...
? is a parameter placeholder that is replaced with the value of the expression you pass with USING when you do EXECUTE. That way don't need to care about escaping, quoting etc. and can't do it wrong.

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.

Using variable in select query

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

Having trouble with concat in stored procedure

Can anyone tell me why I am getting this error in MySql:
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
Here is my code:
CREATE PROCEDURE `msgBoardGetComments2`(
IN _StoryID INT,
IN _RowNum INT
)
BEGIN
DECLARE _sql VARCHAR(1000);
SET _sql := CONCAT('SELECT c.CommentText, c.CommentDate, a.UserName
FROM comments c
LEFT JOIN accounts a
ON c.UserID = a.UserID
LEFT JOIN stories s
ON c.StoryID = s.StoryID
WHERE c.StoryID = ',_StoryID, '
ORDER BY c.CommentDate DESC
LIMIT 10
OFFSET ', _RowNum);
PREPARE stmt1 FROM #_sql;
EXECUTE stmt1;
END
I believe you may be receiving that error when _RowNum is NULL. If this is the case, you can try adding an IF condition to optionally include the OFFSET _RowNum if the _RowNum is NULL. You can test this by printing your query before execution:
SELECT _sql;
--PREPARE stmt1 FROM #_sql;
--EXECUTE stmt1;
Also, I haven't seen the use of an underscore (_) for variable assignment, perhaps that may also be playing a role in this?

Unknown column in 'where clause' with stored procedure

I am using a stored procedure with a prepared statment to find rows from a string of email addresses.
It looks like this:
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `get_users_by_email`(IN emailString VARCHAR(100))
BEGIN
SET #sql = CONCAT('SELECT user_id FROM users WHERE user_email IN (',emailString,')');
PREPARE qry FROM #sql;
EXECUTE qry;
END
I then call the procedure using:
CALL get_users_by_email('me#email.com,you#email.com, etc..');
But, I receive this error:
Unknown column in 'me#email.com' in 'where clause'
The query works if I use it to find numeric values such as:
CALL get_users_by_email('123,456');
Any ideas why it would be erroring on alphanumeric values? The query works fine when it is pulled out of the prepared statement and procedure.
You need string delimiters around your email address:
SET #sql = CONCAT('SELECT user_id FROM users WHERE user_email IN (''',emailString,''')');
If you are using a string, you need to pass it with quotes:
SET #sql = CONCAT('SELECT user_id FROM users WHERE user_email IN (''',emailString,''')');
I used extra quotes to escape. The numbers work since numbers are not interpreted as object names if they aren't delimited.