dynamic column name selection in MySql - mysql

I am stuck in Mysql today with the dynamic column name need in mysql select statement. Let me explain:
sql> select name1 from namescollection.
sql> select name2 from namescollection.
sql> select name3 from namescollection.
So namescollection table has three columns having name1, name2, name3
I would like to query this table in my stored procedure being 1,2,3 as dynamic and would be passed as a variable, but on the simple sql too when i query:
SELECT concat('name','1') FROM `namescollection`
name1 ----- name1 rather fetching name1 field's value.
Can any suggest on this, the right function i need to use rather concat though I know its right to output name1 when I am calling concat but I want to use it as column name.

What you can do is use a prepared statement within your stored procedure which will allow you to execute a string query:
As a simple example:
DELIMITER //
CREATE PROCEDURE selname (IN col VARCHAR(20))
BEGIN
SET #sql = CONCAT('SELECT ', col, ' FROM tbl');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END//
DELIMITER ;
Test it out with this SQLFiddle Demo

Dynamic column name in store procedure Update statement :
DELIMITER //
CREATE DEFINER=`root`#`localhost` PROCEDURE `selname`()
BEGIN
declare cl int ;
declare clvalue int ;
set cl=1;
SET clvalue=1;
while cl < 4 DO
SET clvalue=clvalue*cl;
SET #sql = CONCAT('update test set col',cl, '=',clvalue,' where id=1');
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
set cl=cl+1;
end while;
END //
DELIMITER ;

Related

execute expression stored in a column

I need some help about executing expression(bitwise) stored in a column of a table.
Input :
ID | expression
----|-------------
1 | 1&0
2 | (1&1)|(0&1)
Desired Output :
ID | expression | value
----|-------------|-------
1 | 1&0 | 0
2 | (1&1)|(0&1) | 1
I am trying something like below but it is not executing the expression.
PREPARE stmt from 'select ? into #outvar';
set #invar = '1&0';
execute stmt using #invar;
select #outvar;
The output of above is 1&0 but the desired output is 0.
Actually I want to store the output in a variable as framed in my above pseudo code.
I have built you a procedure to do this
DROP TABLE IF EXISTS test10;
DROP PROCEDURE IF EXISTS `sp_test10`;
create table test10 (ID int, expression VARCHAR(20));
insert into test10 values ( 1 , '1&0');
insert into test10 values ( 2 , '(1&1)|(0&1)');
CREATE PROCEDURE sp_test10 (IN IN_ID int, OUT OUT_VAL INT)
BEGIN
SELECT expression INTO #exp FROM test10 WHERE ID=IN_ID;
SET #q = CONCAT('SELECT ',#exp,' INTO #exp ');
PREPARE stmt1 FROM #q;
EXECUTE stmt1;
DEALLOCATE PREPARE stmt1;
SET OUT_VAL = #exp;
END\\
;
call sp_test10(2,#result);
select #result;
Results :
call sp_test10(1,#result) returns 0
call sp_test10(2,#result) returns 1
http://rextester.com/live/SMLB31207
Using prepared statements, what are sent to server in the second round are treated literally. They can't be part of SQL. You shouldn't use placeholders for this:
SET #invar = '(1&1)&(0&1)';
SET #s = CONCAT('SELECT ', #invar, ' INTO #outvar');
PREPARE stmt FROM #s;
EXECUTE stmt;
SELECT #outvar;

Query not working like it is supposed to

I am trying to get this query to work
delimiter //
CREATE PROCEDURE test2(IN tbl CHAR(64), IN col CHAR(64))
BEGIN
SET #s = CONCAT('SELECT ',col,' FROM ',tbl );
PREPARE stmt FROM #s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
//
delimiter ;
This is the code used to call it
CALL test2(groups,NAME)
And this is the error I get:
1 Unknown column 'groups' in 'field list' SQL2.sql 1 12
The table name is groups, and the column name is NAME - Why is this not working
Well, you have written a stored procedure that takes character strings, and you have passed identifiers.
Try calling it thusly:
CALL test2('groups', 'NAME')

Using Prepared statement in Dynamic view

Here is my code
Drop procedure if exists test//
CREATE PROCEDURE test(IN woeid VARCHAR(15))
BEGIN
SET #w1 := woeid;
SET #sql = CONCAT('CREATE OR REPLACE VIEW temp
AS
SELECT *
FROM test_table gp
WHERE gp.name =', #w1);
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END//
Delimiter ;
call test('ABCD');
I am getting error as
Error code: 1054. Unknown column 'ABCD' in 'where' clause
Please help.
It sounds as though you're needlessly using views, when some other approach would be more appropriate.
However, the reason it isn't working is that you haven't quoted your string literal, so the resulting SQL contains WHERE gp.name = ABCD whereas it at very least needs to be WHERE gp.name = 'ABCD'. You can use MySQL's QUOTE() function for this purpose, but it's better to parameterise the value:
DELIMITER //
DROP PROCEDURE IF EXISTS test//
CREATE PROCEDURE test(IN woeid VARCHAR(15))
BEGIN
SET #w1:=woeid, #sql:=CONCAT('
CREATE OR REPLACE VIEW temp AS
SELECT *
FROM test_table
WHERE name = ?
');
PREPARE stmt FROM #sql;
EXECUTE stmt USING #w1;
DEALLOCATE PREPARE stmt;
SET #w1:=NULL, #sql:=NULL;
END//
DELIMITER ;
CALL test('ABCD');

MySQL stored procedures - How to use parameter in FROM clause

I have the following stored procedure:
DELIMITER ///
CREATE PROCEDURE tmp_test_proc(__TABLE__NAME varchar(255))
BEGIN
SELECT COUNT(*) FROM __TABLE__NAME;
END///
DELIMITER ;
I would like to select from the parameter __TABLE__NAME, but MySQL tells me there is no table __TABLE__NAME... So is there a way to use the value of the parameter in the from clause?
you cannot parameterized table names (as well as column names) by default, you need to create PreparedStatement for this,
DELIMITER ///
CREATE PROCEDURE tmp_test_proc(__TABLE__NAME varchar(255))
BEGIN
SET #sql = CONCAT('SELECT COUNT(*) FROM ', __TABLE__NAME);
PREPARE stmt FROM #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END///
DELIMITER ;

How to use variable as the table identifier in MYSQL

If i have this:
CREATE TABLE ftable (
id INT,
fvalue VARCHAR(14)
);
INSERT INTO ftable VALUES (1,'tableB'),(2,'tableA');
CREATE TABLE tableA (
value VARCHAR(14)
);
SELECT #tmp:=fvalue FROM ftable WHERE id=2;
How do I make it so I can do this:
INSERT INTO #tmp VALUES ('buhambug');
Becuase as far I know that throws a mysql error.Can someone show me a sqlfiddle of the solution? Or maybe I'm thinking about this the wrong way?
You need to use dynamic SQL to use a variable as an object name:
SET #tmp = (SELECT fvalue FROM ftable WHERE id=2);
SET #SQL = CONCAT('INSERT INTO ',#tmp,' VALUES (''buhambug'')');
PREPARE stmt FROM #SQL;
EXECUTE stmt;
SQL FIDDLE
You can't do in static sql.
You can do it in stored procedure:
delimiter $$
drop procedure if exists test_call$$
create procedure test_call(table_in varchar(100))
begin
set #q = concat("select * from ", table_in);
PREPARE stmt FROM #q;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
end$$
delimiter ;
call test_call('TeableA');
drop procedure if exists test_call;
In general dynamic read from dynamic tables is not a good decision