SQL : Running select statement for local string variable - mysql

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.

Related

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

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;

mysql - query inside a query

How is it possible to do the following :
(i am using mysql - phpmyadmin )
this query returns a table name :
Select table_name from Table1 where id = 1
I want to use it inside another query , like :
select val from (Select table_name from Table1 where id = 1)
but this sure does not work, and since phpmyadmin does not support calling stored procedures, could there be any possible solution for this ?
You cannot really do it in a single SQL statement.
You are trying to use data (field value) as metadata (table name), and SQL does not allow this.
You could break it in two statements or write dynamic SQL in a stored procedure. Note that not all client layers support returning resultsets from stored procedures.
you also ma execute dynamic select:
declare v_table_name VarChar(128);
BEGIN
Select table_name into v_table_name from Table1 where id = 1
SET #s = CONCAT('SELECT * FROM ', v_table_name, ' where id = 1');
PREPARE stmt1 FROM #s;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
END;

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;