set variable to column name mysql - mysql

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");

Related

convert comma separated string values into integer values in mysql

I have a comma separated string variable v_combined_prodid .
But i wants to convert comma separated string variable to comma separated int value or in loop where we can update one table with where clause prodid as int.
we cant use FIND_IN_SET(prodid, v_combined_prodid )
we can use stored procedure.
DECLARE v_combined_prodid varchar(800);
set v_combined_prodid ='1,2,3,4,5';
below statement exactly requirement.
update mytable t set t.status=2
WHERE prodid in (1,2,3,4,5)
and t.status=0 ;
You are better off creating a dynamic query and then execute it.
See Mysql dynamically build query string in a stored procedure based on logic for an example.
DECLARE v_combined_prodid varchar(800);
set v_combined_prodid ='1,2,3,4,5';
set #query = CONCAT(' update mytable t set t.status = 2 where prodid in ('
, v_combined_prodid
, ') and t.status = 0');
PREPARE stmt FROM #query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;

table column as variable

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

MySQL select query with where condition using string variables

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

How to get variable value as table name in select statement

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;

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.