convert comma separated string values into integer values in mysql - 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;

Related

How to loop comma separated values into select statement in MySQL stored procedure

I have to send comma separated values into a select statement where it will update values through #sql statement.
I have common table in all Databases I need to update the table column by one update statement in the procedure.
For Example : Input Param will be ('DataBase1','Database2',....., 'Database10')
Below is the sample procedure :
DELIMITER &&
CREATE PROCEDURE update_stmt (IN DBName varchar(100))
BEGIN
Declare DBName = #DB;
**comma seperated values loop and placed into the #DB**
use #DB;
SELECT concat(update #DB.sample SET COL = 0 where ID = \'',ID,'\','; ) as stmt FROM
Test.Sample into #s;
SET #sql = #s
PREPARE stmt from #sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END &&
DELIMITER ;
so that update statement will execute in each of the databases.
Here's another approach. I don't try to split the comma-separated string, I use it with FIND_IN_SET() to match schema names in INFORMATION_SCHEMA.TABLES. This filters to schemas in the list that actually exist, and tables that actually exist in that schema.
Then use a cursor to loop over the matching rows, so you don't have to split any strings, which is awkward to do in a stored procedure.
I supposed that you would want to specify the id of the row to update too, so I added that to the procedure parameters.
Also notice the use of quotes when I create #sql. You can concatenate strings, but those must be quote-delimited like any other string literal. Variables must not be inside the quoted string. There's no feature to expand variables inside string literals in MySQL.
DELIMITER &&
CREATE PROCEDURE update_stmt (IN schema_name_list VARCHAR(100), IN in_id INT)
BEGIN
DECLARE done INT DEFAULT false;
DECLARE schema_name VARCHAR(64);
DECLARE cur1 CURSOR FOR
SELECT TABLE_SCHEMA FROM INFORMATION_SCHEMA.TABLES
WHERE TABLE_NAME = 'sample' AND FIND_IN_SET(TABLE_SCHEMA, schema_name_list);
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = true;
SET #id = in_id;
OPEN cur1;
schema_loop: LOOP
FETCH cur1 INTO schema_name;
IF done THEN
LEAVE schema_loop;
END IF;
SET #sql = CONCAT('UPDATE `', schema_name, '`.sample SET col = 0 WHERE id = ?');
PREPARE stmt FROM #sql;
EXECUTE stmt USING #id;
DEALLOCATE PREPARE stmt;
END LOOP;
CLOSE cur1;
END &&
DELIMITER ;
Frankly, I hardly ever use stored procedures in MySQL. The procedure language is primitive, and the tasks I see people try to do in stored procedures could be done a lot more easily in virtually every other programming language.

Explain the stored procedure described below

CREATE DEFINER=`root`#`localhost` PROCEDURE `get_plan_images`(
_list varchar(2000)
)
BEGIN
SET #LIST=_list;
set #sql = concat('SELECT plan_id, plan_image
FROM ibuild.plan_images
where plan_id in (', #LIST , ')');
PREPARE q FROM #sql;
execute q;
END
What does concat do here? And what does this statement means PREPARE q FROM #sql;
CONCAT simply merges two or more pieces of text together. In the example above, #LIST contains a list of ids passed in to the procedure. After the CONCAT, #sql becomes a string that contains something like:SELECT plan_id, plan_image FROM ibuild.plan_images where plan_id in (1,2,3)
See here: MySQL CONCAT Function
The PREPARE statement just gives the statement a name so you can execute it. See here: MySQL PREPARE

Calling stored procedure with a string to use in query

I have a stored procedure where i need to pass a string to use in the query.
Stored procedure example:
BEGIN
SET #query = query;
SELECT * FROM test WHERE #query
END
How I would like to call it with a string:
CALL proceduretet('activity_id = 1 OR activity_id = 2')
The query can be different each time, sometimes there will be 1 activity_id and sometimes 4 or more.
I have tried to pass it as a varchar and text, but it won't work.
So is there a way to pass a string to stored procedures and use it in the query?
Regards, Andreas
The code would look like:
BEGIN
SET #query = query;
SET #sql = concat('SELECT * FROM TEST WHERE ', #query);
PREPARE stmt from #sql;
EXECUTE stmt;
END;

set variable to column name 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");

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.