Is it possible to execute a string in MySQL? - mysql

I have to convert a MSSQL stored proc that passes a varchar that is a query:
INSERT INTO Results
EXEC (#Expresion);
This isn't working. I'm pretty sure that EXEC and EXECUTE aren't MySQL commands, but CALL doesn't work either.
Does anyone know if it's even possible to have something like JavaScript's eval function for MySQL?

I think you're looking for something like this:
SET #queryString = (
SELECT CONCAT('INSERT INTO user_group (`group_id`,`user_id`) VALUES ', www.vals) as res FROM (
SELECT GROUP_CONCAT(qwe.asd SEPARATOR ',') as vals FROM (
SELECT CONCAT('(59,', user_id, ')') as asd FROM access WHERE residency = 9
) as qwe
) as www
);
PREPARE stmt FROM #queryString;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET #asd = NULL;

This is the SQL equivalent of eval(my_string);:
#Expression = 'SELECT "Hello, World!";';
PREPARE myquery FROM #Expression;
EXECUTE myquery;
Basically I combined the existing answers, neither tells you how to do eval exactly.
If you want to add parameters, you can use this:
#username = "test";
#password = "asdf";
#Expression = 'SELECT id FROM Users WHERE name = ? AND pass = ?;'
PREPARE myquery FROM #Expression;
EXECUTE myquery USING #username, #password;
And to answer the original question exactly:
#Expression = 'SELECT "Hello, World!";'
PREPARE myquery FROM #Expression;
INSERT INTO Results
EXECUTE myquery;
Note that the PREPARE ... FROM statement wants a session variable (prefixed with #). If you try to pass a normal variable, it will throw its hands up in the air and it just won't care.

EXECUTE is a valid command in MySQL. MySQL reference manual

The EXECUTE MySQL command can only be used for one prepared statement.
If case you want to execute multiple queries from the string, consider saving them into file and source it, e.g.
SET #query = 'SELECT 1; SELECT 2; SELECT 3;';
SELECT #query INTO OUTFILE '/tmp/temp.sql';
SOURCE /tmp/temp.sql;

Related

syntax error in prepare statement

set formula= REPLACE(upper(formula),upper(C_PHD_TAG), tagval);
set #replacevalue=CONCAT('SELECT ',#formula);
PREPARE myquery FROM #replacevalue;
EXECUTE myquery;
formula is'448.1879+405.8730+431.2464+407.9746' how to calculate this equation?
One approach is to use the EXECUTE method for prepared statement:
set #formula = '448.1879+405.8730+431.2464+407.9746';
set #query = CONCAT('SELECT ',#formula);
PREPARE myquery FROM #query;
EXECUTE myquery;
To store the result in a variable:
set #formula = '448.1879+405.8730+431.2464+407.9746';
set #query = concat('SELECT ',#formula, ' into #result');
prepare myquery from #query;
execute myquery;
select #result;
In the above,
#formula - holds the original formula for which the value should be calculated
#query - SQL statement that will be evaluated and produce the result of the formula
#result - variable that will contain the result after execution
myquery - name of the prepared statement (created by PREPARE, executed by EXECUTE)
See the link for the MySQL Execute Documentation

MySQL select query with where condition using string variables

Myself trying to pass string variable to where condition in MySQL query as given in this stack overflow answer as given below.
select #start := ' and Id=21';
select * from myTable where 1=1 #start;
So how can I use string variable with where condition in MySQL queries. The variables are set dynamically and the query runs within procedure.
EDIT: I also tried
SET #start = ' Id=21 ';
select * from myTable where (select #start);
But no use.
No you cannot do that. The columns and the condition in the select clause needs to be fixed when you are preparing the select statement.
So you cannot make a dynamic where clause statement like the one you posted. In that example, the values in the column are dynamic not the column names.
The manual says:
A conditional object consists of one or more conditional fragments
that will all be joined by a specified conjunction. By default, that
conjunction is AND.
I believe what you are attempting is to create a Dynamic Query using EXEC command.
You can create a varchar variable with the SQL statement and then execute it with EXEC, here an example taken from
https://www.mssqltips.com/sqlservertip/1160/execute-dynamic-sql-commands-in-sql-server/
If you want to do something like
DECLARE #city varchar(75)
SET #city = 'London'
SELECT * FROM customers WHERE City = #city
This is the Dynamic Query creation.
DECLARE #sqlCommand varchar(1000)
DECLARE #columnList varchar(75)
DECLARE #city varchar(75)
SET #columnList = 'CustomerID, ContactName, City'
SET #city = '''London'''
SET #sqlCommand = 'SELECT ' + #columnList + ' FROM customers WHERE City = ' + #city
EXEC (#sqlCommand) --This does the magic
/*
just a heads up, the user impersonating the execution needs credentials for EXEC command.
*/
Store part of your query
SET #start = ' and Id=21';
Store your query concatenating its parts
SET #s = CONCAT('select * from myTable where 1=1 ', #start);
Prepare a statement for execution
PREPARE stmt FROM #s;
EXECUTE executes a prepared statement
EXECUTE stmt;
Release the prepared statement
DEALLOCATE PREPARE stmt;
All together:
SET #start = ' and Id=21';
SET #s = CONCAT('select * from myTable where 1=1 ', #start);
PREPARE stmt FROM #s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
More Details on the MySQL manual: https://dev.mysql.com/doc/refman/5.7/en/sql-syntax-prepared-statements.html

MYSQL How to use a variable for the OutFile

I can't find how to use a variable as an an Outfile.
DECLARE wOutFile CHAR(256);
SET wOutFile = CONCAT('c/data/',wDateStr,'.csv');
SELECT * FROM sometable
INTO OUTFILE wOutFile;
The above renders an error on the last line. The syntax parser in MySQL Workbench doesn't like the wOutFile on the last line.
Is there a way to tell the parser to use the contents of the variable?
I tried to search for a while but I must not be phrasing my question well.
If you want to make new statement from the strings, then you should use prepared statements -
DECLARE wOutFile CHAR(256);
SET wOutFile = CONCAT('c/data/',wDateStr,'.csv');
SET #var = CONCAT('SELECT * FROM sometable INTO OUTFILE ', wOutFile);
PREPARE stmt FROM #var;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

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.

use a variable for table name in mysql sproc

I'm trying to pass a table name into my mysql stored procedure to use this sproc to select off of different tables but it's not working...
this is what I"m trying:
CREATE PROCEDURE `usp_SelectFromTables`(
IN TableName varchar(100)
)
BEGIN
SELECT * FROM #TableName;
END
I've also tried it w/o the # sign and that just tells me that TableName doesn't exist...which I know :)
SET #cname:='jello';
SET #vname:='dwb';
SET #sql_text = concat('select concept_id,concept_name,',#vname,' from enc2.concept a JOIN enc2.ratings b USING(concept_id) where concept_name like (''%',#cname,'%'') and 3 is not null order by 3 asc');
PREPARE stmt FROM #sql_text;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
An extra bit that caused me problems.
I wanted to set the table name and field dynamically in a query as #kyle asked, but I also wanted to store the result of that query into a variable #a within the query.
Instead of putting the variable #a into the concat literally, you need to include it as part of the string text.
delimiter //
CREATE PROCEDURE removeProcessed(table_name VARCHAR(255), keyField VARCHAR(255), maxId INT, num_rows INT)
BEGIN
SET #table_name = table_name;
SET #keyField = keyField;
SET #maxId = maxId;
SET #num_rows = num_rows;
SET #sql_text1 = concat('SELECT MIN(',#keyField,') INTO #a FROM ',#table_name);
PREPARE stmt1 FROM #sql_text1;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
loop_label: LOOP
SET #sql_text2 = concat('SELECT ',#keyField,' INTO #z FROM ',#table_name,' WHERE ',#keyField,' >= ',#a,' ORDER BY ',#keyField,' LIMIT ',#num_rows,',1');
PREPARE stmt2 FROM #sql_text2;
EXECUTE stmt2;
DEALLOCATE PREPARE stmt2;
...Additional looping code...
END LOOP;
END
//
delimiter ;
So in #sql_text1 assign the result of the query to #a within the string using:
') INTO #a FROM '
Then in #sql_text2 use #a as an actual variable:
,' WHERE ',#keyField,' >= ',#a,' ORDER BY '
It depends on the DBMS, but the notation usually requires Dynamic SQL, and runs into the problem that the return values from the function depend on the inputs when it is executed. This gives the system conniptions. As a general rule (and therefore probably subject to exceptions), DBMS do not allow you to use placeholders (parameters) for structural elements of a query such as table names or column names; they only allow you to specify values such as column values.
Some DBMS do have stored procedure support that will allow you to build up an SQL string and then work with that, using 'prepare' or 'execute immediate' or similar operations. Note, however, that you are suddenly vulnerable to SQL injection attacks - someone who can execute your procedure is then able to control, in part, what SQL gets executed.