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;
Related
I'm getting a syntax error in my stored procedure when trying to use a variable as a reference to a tables column.
BEGIN
SET #mycolumn = (SOME SELECT STATEMENT RETURNING MY COLUMN);
SELECT a.#mycolumn FROM mytable as a;
END
Question: What is wrong with my syntax?
It looks like you're trying to do dynamic SQL. Here is one way to do it:
BEGIN
SET #mycolumn = (SOME SELECT STATEMENT RETURNING MY COLUMN);
DECLARE #sql varchar(20000);
SET #sql = CONCAT('SELECT a.', #mycolumn, ' FROM mytable as a';
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
Jordan,
You might need to use table variable or Dynamic SQL for this.
Here is how I do this with table variable.
Declare #table as table (columnName dataType.
Insert into #table
SOME SELECT STATEMENT RETURNING YOUR COLUMN
Results by running the below query:-
SELECT * FROM #table
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
I'm looking for a way to generate valid HTML code within MySQL (without PHP) by converting any query output into an HTML table.
Here's my progress so far and evidently, I'm stuck. I hope I can get some help, thanks.
1. "dynSQL" - A procedure to take any Select query and create a named table out of it
Since MySQL doesn't allow dynamic queries in functions, I'm calling a procedure that creates a named table, tmp. I can't use a temporary table because info about temporary tables is not available in information_schema (in mysql 5.6)
CREATE DEFINER=`root`#`%` PROCEDURE `dynSQL`(SQL_QUERY TEXT)
BEGIN
set #SQLQ := 'Drop table if exists tmp;';
PREPARE stmt from #SQLQ;
Execute stmt;
SET #SQLQ := concat('create table tmp as ',SQL_QUERY);
PREPARE stmt from #SQLQ;
Execute stmt;
-- I'm adding a auto increment ID column to be able to loop through the rows later
SET #SQLQ := "ALTER TABLE tmp add column CustColHTML_ID INT NOT NULL AUTO_INCREMENT FIRST, ADD primary KEY Id(CustColHTML_ID)";
PREPARE stmt from #SQLQ;
Execute stmt;
DEALLOCATE PREPARE stmt;
END
2. "MakeHTML" - Function to read from the table tmp and return a formatted HTML table
CREATE DEFINER=`root`#`%` FUNCTION `MakeHTML`() RETURNS text CHARSET utf8
DETERMINISTIC
BEGIN
DECLARE HTML text default "<TABLE><TR>";
DECLARE rowCount int default 0;
DECLARE i int default 0;
select concat('<TR>',group_concat('<TD>',column_name,'</TD>' separator ''),'</TR>') into html from information_Schema.`columns` where table_name='tmp';
Select max(CustColHTML_ID) into rowCount from `tmp`; -- Set the row counter
WHILE i<=rowCount DO
-- What do I do here? How do I loop through the columns of table tmp?
set i:=i+1;
END WHILE;
RETURN HTML;
END
As you can see, I'm stuck at looping through the unknown and dynamic columns of table tmp. I read about how a cursor can be used here, but all the examples I saw make use of known columns and assign those into named variables. However, since the query itself is dynamic, I wouldn't know the names of the columns.
I'd really appreciate your time and assistance, thanks!
p.s. I've posted this as a new question because my earlier question was marked as closed as being too broad. I subsequently edited my question but it was still showing as Closed. I've therefore deleted the older question and replaced it with this one.
With a sample table as such:
CREATE TABLE tmp (ID INT, Col1 INT, Col2 INT);
The SQL you would need to generate your HTML is:
SELECT CONCAT('<table>', GROUP_CONCAT(CONCAT('<tr><td>',ID,'</td><td>',Col1,'</td><td>',Col2,'</td><tr>')), '</table>')
FROM tmp;
You can generate this using the INFORMATION_SCHEMA:
SELECT CONCAT
(
'SELECT CONCAT(''<table>'', GROUP_CONCAT(CONCAT(''<tr>'', ',
GROUP_CONCAT(CONCAT('''<td>'',', COLUMN_NAME, ',''</td>''')),
', ''</tr>'')), ''</table>'') FROM tmp'
)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'tmp';
It is then just a case of executing this:
SET #SQL = (
SELECT CONCAT
(
'SELECT CONCAT(''<table>'', GROUP_CONCAT(CONCAT(''<tr>'', ',
GROUP_CONCAT(CONCAT('''<td>'',', COLUMN_NAME, ',''</td>''')),
', ''</tr>'')), ''</table>'') FROM tmp'
)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'tmp'
);
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Example on SQL Fiddle
ADDENDEUM
Forgot to include table headers:
SET #SQL = (
SELECT CONCAT
(
'SELECT CONCAT(''<table><tr>'',',
GROUP_CONCAT(CONCAT('''<th>'',''', COLUMN_NAME, ''',''</th>''')),
', ''</tr>'', GROUP_CONCAT(CONCAT(''<tr>'', ',
GROUP_CONCAT(CONCAT('''<td>'',', COLUMN_NAME, ',''</td>''')),
', ''</tr>'')), ''</table>'') FROM tmp'
)
FROM INFORMATION_SCHEMA.COLUMNS
WHERE TABLE_NAME = 'tmp'
);
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Example on SQL Fiddle
How do I cache dynamic query from store procedure?
Right now I have created my store procedure like this :
CREATE PROCEDURE usp_MyProcedure (
IN UserID INT,
....
)
BEGIN
SET #sqlQuery = CONCAT("SELECT Name From Users WHERE UserID > ", UserID, " AND UserID IN ( SELECT UserID FROM OtherTable WHERE UserID = ", UserID, " ) Order by Name")
PREPARE stmt FROM #sqlQuery;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END;
But this kind of query does not cached. so, every time it gets more time to execute/process query.
Now I have tried some other method like this:
CREATE PROCEDURE usp_MyProcedure (
IN UserID INT,
....
)
BEGIN
SET #UserID = UserID;
SET #sqlQuery = "SELECT Name From Users WHERE UserID > ? AND UserID IN ( SELECT UserID FROM OtherTable WHERE UserID = ? ) Order by Name";
PREPARE stmt FROM #sqlQuery;
EXECUTE stmt #UserID, #UserID; -- here i passed same variable twice.
DEALLOCATE PREPARE stmt;
END;
In the above case I have to pass same variable (#UserID) twice, because it is used 2 times in my query. but this job is very hectic in long or complex query. so, how do I avoid this?
One another method I tried as follows:
CREATE PROCEDURE usp_MyProcedure (
IN UserID INT,
....
)
BEGIN
SET #UserID = UserID;
SET #sqlQuery = "SELECT Name From Users WHERE UserID > #UserID AND UserID IN ( SELECT UserID FROM OtherTable WHERE UserID = #UserID ) Order by Name";
PREPARE stmt FROM #sqlQuery;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END;
But above query again does not cached. so, execution time is very long. and this type of variable declared as session global variable has may be conflict with another store procedure's variable. because I have call store procedure within this store procedure and variable name should be same in another store procedure.
So, let me know what is the best solution for the same.
Thanks.
Sorry just posted a mistaken one,
DELIMITER //
CREATE PROCEDURE yourprocedurenamehere(IN state CHAR(2))
BEGIN
SET #mystate = state;
SET #sql = CONCAT('SELECT * FROM BLABLABLA WHERE BLA = ?');
PREPARE stmt FROM #sql;
EXECUTE stmt USING #mystate;
END;
//
Sorry pal, just edited my code hahaha I got this wrong
A short answer is that there is no way to do it. In theory, you could identify prepared statement name with sha1(prepared statement query text), and use this as a statement handle. But there is no way to dynamically execute a statement which name is stored in a variable or in a table: EXECUTE itself is not allowed in Dynamic SQL query text.
A different question is whether you need a Dynamic SQL in your example at all, it seems like a standard SQL stored procedure parameterized with input parameters could do just fine.
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.