SET Project_List_val=CONCAT(Project_Number_val,'_List');
Insert Into test (Manthan_Panel_Id) select Manthan_Panel_Id from Project_List_val where Project_Number_val='9';
In the insert statement there is the variable named 'Project_List_val' which consist of table name as concated in the above step. This statement is not taking the content of the variable as table name instead it is taking 'Project_List_val' as table name and giving table not found error.
Any suggestions?
By default you cannot parameterized table names and column names so you need to create Dynamic SQL for that,
SET #Project_List_val = CONCAT(Project_Number_val, '_List');
SET #projNum = 9;
SET #sql = CONCAT(' INSERT INTO test (Manthan_Panel_Id)
SELECT Manthan_Panel_Id
FROM ', #Project_List_val, '
WHERE Project_Number_val = ?');
PREPARE stmt FROM #sql;
EXECUTE stmt USING #projNum;
DEALLOCATE PREPARE stmt;
Related
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;
i have table and i want to add column but the name of column will be variable
like this :
$coulName = col_1_2;
ALTER TABLE `table name` ADD `$coulmName` DOUBLE NOT NULL DEFAULT '0' AFTER `col2`;
how can i do that ?
You need to use a prepared statement for this:
SET #colName = 'col_1_2';
SET #s = CONCAT('ALTER TABLE `mytable` ADD `', #colName,
'` DOUBLE NOT NULL DEFAULT 0 AFTER `col2`');
PREPARE stmt1 FROM #s;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
Within MySQL you can only achieve this using prepared statements because you cannot tie a variable to a table or column name. This means that you have to assemble the sql statement in a string and execute it.
However, you can accomplish this from your application code as well - the variable name suggests that you may use php. The same applies: you have to concatenate the sql statement string, cannot use parameters.
Code would look sg like the below in MySQL:
#coulName = 'col_1_2';
#sql = 'ALTER TABLE `table name` ADD `',#coulmName,'` DOUBLE NOT NULL DEFAULT '0' AFTER `col2`;
PREPARE stmt1 FROM #sql;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
However, I'm not sure if it a really good idea to regularly and dynamically change the existing data structure. That usually indicates poor database design.
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
I am trying to loop through a table adl_weight that has a column with the exact names of a column from another table adl_activities. I am trying to grab the column name from the table and use that to grab the value of the column on the second table.
Is it possible to do this with mysql? I have tried to use prepared statements but so far these aren't working.
set i = 1;
select count(*) from adl_weight into n;
WHILE(i<n) DO
set tmp_condition =(select user_condition from adl_weight where row_number = i);
set tmp_score = (select tmp_condition from adl_activities where userid = id);
if(tmp_score > 0) then
#do items here
end if;
END WHILE;
If I understand you correctly, you need to grab a column whose name is defined in a variable.
The problem is that mysql doesn't let you insert variables as anything other than values, but you can create a new string which contains a command with the variable's value as the column name and execute that. Here's an example:
SET #sql = CONCAT("SELECT `", #columnName, "` FROM tableA");
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
Edit:
If you want to select into a variable instead, you can use this:
SET #sql = CONCAT("SELECT ", #columnName, "` FROM tableA INTO #result");
I have this below piece of code. I would like to populate the KPI_RESULTS table using computed data from variable data. The variable data receives different fomulas. eg( n1*n7)*100 depending on the definition of the KPI fomula by the engineer. n1 ----n! are column names.
Am however getting an error when I try to execute the below scripts.
enter code here
set #data = 'n2/n1';
set #s = Concat("select datetime , element NODE,",#data," RESULTS from loas");
PREPARE STMT FROM #s;
INSERT INTO KPI_results(date_time,node_name,results) values(execute STMT );
That's unfortunately not supported. You'll have to PREPARE the dynamically generated INSERT query you want to run instead:
mysql> set #formula='n2/n1'
mysql> set #sql = CONCAT('INSERT INTO KPI_results SELECT foo, bar, ', #formula, ' FROM t')
mysql> PREPARE stmt FROM #sql
mysql> EXECUTE stmt