Escape string gets un-escaped in mysql concat function - mysql

I have following SP:
CREATE PROCEDURE sp_test
(
text_data varchar(50)
)
BEGIN
SET #var_query = CONCAT('SELECT * FROM sample_table WHERE col="',text_data,'"');
PREPARE stmt FROM #var_query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END;
I call this SP like so CALL sp_test('Screen size 4.3\"'). I get an error. Then if I check value of #var_query variable, this is how it looks.
+-------------------------------------------------------+
| #var_query |
+-------------------------------------------------------+
| SELECT FROM sample_table WHERE col="screen size 4.3"" |
+-------------------------------------------------------+
As you can see the escaped " is getting un-escaped. If I hit this select statement directly with escaped double-quotes, it runs fine. So it means concat is removing un-escaping the escaped characters. How to tackle this issue?

This is how it have to be:
SET #var_query = SELECT * FROM sample_table WHERE col=?';
SET #data = text_data;
PREPARE stmt FROM #var_query;
EXECUTE stmt USING #data;
DEALLOCATE PREPARE stmt;
while
Escape string gets un-escaped in mysql concat function
is correct and the only proper behavior.

Related

Using a variable OUTFILE in a MySQL scheduled event

I am using phpMyAdmin to try to schedule an event that runs every hour. I need it to select data from one of my tables and export it to csv that has a unique name which includes the current timestamp. Outside of an event, I can successfully output from my table to a csv like so:
SET #TimeStamp = DATE_FORMAT(NOW(),'__%Y_%m_%d__%H.%i.%s');
SELECT CONCAT(
'SELECT form_value INTO OUTFILE \'D:/Websites/RTP/contact_form_data/form_data_',
#TimeStamp,
'.csv\' ',
'FROM wp_db7_forms'
) INTO #SQL;
PREPARE stmt from #SQL;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
However, I can't for the life of me figure out how to get this working in an event. phpMyAdmin doesn't give very specific error messages, but it seems that the event doesn't like the fact that I am using a variable (it also doesn't seem to like CONCAT). From my research, I've found that this may be because each event executes in a new session, and user-defined variables have session scope.
I tried creating a stored procedure to execute this same block of code, but that experiences similar issues.
Any ideas on an approach I can take to get my code to properly execute in an event?
Try this.
SET #sql =
CONCAT(
'SELECT form_value INTO OUTFILE \'D:/Websites/RTP/contact_form_data/form_data_',
DATE_FORMAT(NOW(),'__%Y_%m_%d__%H.%i.%s'),
'.csv\' ',
'FROM wp_db7_forms'
) ;
PREPARE stmt from #SQL;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
The session variable for time is not needed and the session variable #sql must be set as show in the code
This can be saved in mysql 8 and Workbench
DELIMITER $$
CREATE EVENT export_contact_Form_data
ON SCHEDULE AT CURRENT_TIMESTAMP + INTERVAL 1 MINUTE
ON COMPLETION PRESERVE
DO BEGIN
SET #sql =
CONCAT(
'SELECT form_value INTO OUTFILE \'D:/Websites/RTP/contact_form_data/form_data_',
DATE_FORMAT(NOW(),'__%Y_%m_%d__%H.%i.%s'),
'.csv\' ',
'FROM wp_db7_forms'
) ;
PREPARE stmt from #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;
This runs only once in one minute, so that you can i peace check
every thing
and of course the delete query
DROP EVENT IF Exists export_contact_Form_data;

How to set the result of a query as a queryable table?

I am trying to use the result of a query as a table.
This query works fine:
SELECT date, number FROM `table_A`
The query below as well --> its result is table_B as a string of character not the table itself
SELECT nametable FROM `list_repository` WHERE id=1
But the combined one does not:
SELECT date, number FROM (SELECT nametable FROM `list_repository` WHERE id=1) A
I expect the resulting query to be
SELECT date, number FROM `table_B`
I tried to set a variable but it does not work either:
DECLARE x VARCHAR(150) ;
SET table=( SELECT `nametable` FROM `list_repository` WHERE id=1);
SELECT * from `table`. But it would not work
Thank you for your help!
Identifiers (db, table, column names etc) in SQL are static. Therefore you can't populate them at run-time. But you can build a query as a string and execute it via dynamic SQL. Something along the lines of
SET #sql = NULL;
SELECT CONCAT("SELECT * FROM ", nametable)
INTO #sql
FROM list_repository
WHERE id = 1;
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
An example of wrapping it up into a stored procedure
DELIMITER //
CREATE PROCEDURE sp1 (IN id INT)
BEGIN
SET #sql = NULL;
SELECT CONCAT("SELECT * FROM ", nametable)
INTO #sql
FROM list_repository
WHERE id = id;
SELECT #sql;
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END//
And then invoking it
CALL sp1(1);

mysql - Using Concat In Stored Procedure Dynamic Query

To do point, I have simple query like
SELECT * FROM mytable WHERE concat(firstName, ' ', lastName) in ('Adan Jack');
Query above run smoothly. But how if I combine that condition using Dynamic Query that using concat before?
I did this:
BEGIN
set #cond = concat(concat("firstName"," ", "lastName"), " in ('Adan Jack')";
set #query = concat("SELECT * FROM mytable WHERE ", #cond);
PREPARE stmt FROM #query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
But no result and cause error.
Thanks.

single quotes in stored procedure update MYSQL

I'm trying a simple update using a stored proc using data from a web service but it is failing saying Unknown column 'USERNAME' in 'field list' due to the single quotes not being recognised in the stored proc.
BEGIN
UPDATE PYBUsers set IsMember = 1 where user = p_user;
END
as you can see the p_user is supplied but the web service and does not have single quotes so gets rejected. I have also tried
SET #query = CONCAT('UPDATE PYBUsers set IsMember = 1 where user = \'', p_user, '''');
and
SET #query = CONCAT('UPDATE PYBUsers set IsMember = 1 where user = ', "'",p_user,"'");
PREPARE stmt FROM #query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt
but no luck. is there an easy solution that I'm missing?
Try
SET #query = CONCAT('UPDATE PYBUsers set IsMember = 1 where user = ''',p_user,'''');
PREPARE stmt FROM #query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt
To add a single quotes into a string you have to put two single quotes together i.e.
'This is Dan''s string; Single quote is inserted between the n and s
''''; this one is a little awkward to read, but here goes. The first quote opens the string, the next two quotes generate a single quote in the string. The final quote closes the string.
INSERT INTO myTable values ('''')
The above would result in one quote being stored in the table

IN Clause dont work in MySQL for me

I am passing my parameter as 'Suburbun','Indigo' to retrieve records matching both Campaigns in below Stored Procedure created in MySql.
CREATE PROCEDURE `DemoSP`(Campaign VARCHAR(3000))
BEGIN
SET #query = CONCAT('Select * from vicidial_log WHERE campaign_id IN (?)');
PREPARE stmt FROM #query;
SET #CampaignID = Campaign;
EXECUTE stmt USING #CampaignID;
DEALLOCATE PREPARE stmt;
END;
It Doesn't give any rows!
But when i pass only 'Suburbun' in SP, it gives 6 Rows!
Where am i going wrong?
--Answer !
I tried as Lee Fentress commented in http://www.poolofthought.com/index.php/2008/12/28/a-comma-seperated-list-as-parameter-to-mysql-stored-procedure/ and peterm answer reflected similar coding,
It worked!
Thanks, but i find this negative mark as compared to SQL Server.
Gee, Thank you Guys!!
You won't be able to use USING in this case. You can just build the full query sting and execute it without parameters
DELIMITER $$
CREATE PROCEDURE DemoSP(Campaign VARCHAR(3000))
BEGIN
SET #query = CONCAT('SELECT * FROM vicidial_log WHERE campaign_id IN (', Campaign, ')');
PREPARE stmt FROM #query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END$$
DELIMITER ;
Note: make sure that delimited values that you pass in Campaign are properly quoted (like you said they are) and quotes in values, if there is any, are escaped.
Here is SQLFiddle demo
Try this:
There is no need to use PREPARE STATEMENT. You can get the result using FIND_IN_SET() function
SELECT * FROM vicidial_log WHERE FIND_IN_SET(campaign_id, Campaign)
try this
"Select * from vicidial_log WHERE campaign_id IN ('?')"
instead of
'Select * from vicidial_log WHERE campaign_id IN (?)'