MYSQL How to use a variable for the OutFile - mysql

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;

Related

MySQL - Is it possible to pick a value from a field as an table for "from" or "join" queries? [duplicate]

I am trying to executing a mysql query like this
SET #id := '47';
SET #table := #id+'_2013_2014_voucher';
SELECT * FROM #table;
Delete FROM #table where id=#id
It showing error like this
[Err] 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 '#table' at line 1
How I can achieve that?
The usage of dynamic table names within the query is best with Prepared Staments,
also in mysql for concatenation the function is concat
SET #id := '47';
SET #table := concat(#id,'_2013_2014_voucher');
set #qry1:= concat('select * from ',#table);
prepare stmt from #qry1 ;
execute stmt ;
You can do it for the delete query as well
You need to use prepared statements for dynamic table name. Prepared statements support parameters, but you can't use them for table names.
Also to put strings together you have to use CONCAT().
Oh, and you have to do all this in a stored procedure.
Create one like this:
DELIMITER $$
CREATE PROCEDURE sp_exec_dynStmt()
BEGIN
SET #id := 47; /*The single-quotes made it a string, that's not necessary*/
SET #table := CONCAT(#id, '_2013_2014_voucher');
SET #sql := CONCAT('SELECT * FROM ', #table, ';');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET #sql = CONCAT('DELETE FROM ', #table, ' WHERE id = ?;'); /*The id can be a parameter, but not the table name*/
PREPARE stmt FROM #sql;
EXECUTE stmt USING #id;
END $$
DELIMITER ;
Then execute it like this:
CALL sp_exec_dynStmt();
try changing that line with
SET #table = '`' + #id+'_2013_2014_voucher`';
usually I declare variable in this way
SET #id = '47'; (without :)
you should use only : with SET, := to assigning variable in a SELECT

Table in FROM clause defined by variable in MySQL

I want to create a SQL script for MySQL 5.7 that inserts data from a table of a database origin into a table of another target database.
I want to have this source-database defined by a variable.
USE my_target_db;
SET #origin_db='my_origin_db';
SET #origin_table = concat(#origin_db,'.','tablename');
INSERT INTO target_table SELECT * FROM #origin_table;
Variables are used in various example to define column names but I never seen a way to define a table with it.
Is anyone has a trick for this ?
Variables won't use in table name in MySQL. You only can use a prepared statement for dynamic build query. For example:
USE my_target_db;
SET #origin_db='my_origin_db';
SET #origin_table = CONCAT(#origin_db,'.','tablename');
SET #query = CONCAT('INSERT INTO target_table SELECT * FROM ', #origin_table);
PREPARE stmt FROM #query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
You can read more detail about it in official documentation
You can use Prepared Statement like this:
USE my_target_db;
SET #origin_db='my_origin_db';
SET #origin_table = concat(#origin_db,'.','tablename');
SET #qry1 = concat('INSERT INTO target_table SELECT * FROM ', #origin_table);
PREPARE stmt1 from #qry1;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;

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.

Is it possible to execute a string in 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;