SQL Stored Procedure Variable - mysql

i am testing this stored procedure thing and i tried using variables,
BEGIN
DECLARE #day int;
SET #day = 1;
IF (1 = 1) THEN
SET #query = 'SELECT #day';
END IF;
PREPARE stmt FROM #query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
this works perfectly fine with a different query and without declaring a variable,i know there is something wrong with the variables and i have researched a lot about this and i cant find any answers. i have this error

If you are on SQL-Server, you must declare the variable: #query.

Just got it.
I just need to do SET #day := 1; instead of SET #day = 1;

Related

MySQL SELECT Name of Stored Procedure and CALL it by that name [duplicate]

I have mysql stored procedure and i want to call to that and procedure name in a variable i used prepared statements but it gave me an error ,
im not a expert in mysql.
here is the prepared statement
> PREPARE stmt1 FROM 'CALL ? (?,?,?)';
SET #q = 'sys_search';
SET #a ='All_Employees';
SET #b = 1;
SET #c = 1;
EXECUTE stmt1 USING #q,#a,#b,#c;
can any one give me the solution?
#Rahul , #Tim Biegeleisen Thank you for your responses.
I used this statements to work done.
SET #q = 'sys_search';
SET #q2 = CONCAT('CALL ',#q,'(?,?,?)');
PREPARE stmt1 FROM #q2;
SET #a = 'All_Employees';
SET #b = 1;
SET #c = 1;
EXECUTE stmt1 USING #a, #b,#c;
I don't think you can execute a stored procedure using dynamic query. Rather create the dynamic query with the SELECT involved in your procedure and execute that.

Call to stored procedure , when procedure name in a variable in mysql

I have mysql stored procedure and i want to call to that and procedure name in a variable i used prepared statements but it gave me an error ,
im not a expert in mysql.
here is the prepared statement
> PREPARE stmt1 FROM 'CALL ? (?,?,?)';
SET #q = 'sys_search';
SET #a ='All_Employees';
SET #b = 1;
SET #c = 1;
EXECUTE stmt1 USING #q,#a,#b,#c;
can any one give me the solution?
#Rahul , #Tim Biegeleisen Thank you for your responses.
I used this statements to work done.
SET #q = 'sys_search';
SET #q2 = CONCAT('CALL ',#q,'(?,?,?)');
PREPARE stmt1 FROM #q2;
SET #a = 'All_Employees';
SET #b = 1;
SET #c = 1;
EXECUTE stmt1 USING #a, #b,#c;
I don't think you can execute a stored procedure using dynamic query. Rather create the dynamic query with the SELECT involved in your procedure and execute that.

Syntax Error in MySQL stored procedure

The below SP is not giving any result even though there are 48 rows as per the where clause
BEGIN
DECLARE SelectClause VARCHAR(2000);
if v_mode='SearchByString' then
SET SelectClause ='select SURVEY_USER.username,SURVEY.* from SURVEY, SURVEY_USER';
if v_SearchString is not null then
SET SelectClause=CONCAT(#SelectClause,' where ');
Set SelectClause=CONCAT(#SelectClause,v_SearchString);
end if;
SET SelectClause=CONCAT(#SelectClause,' order by SURVEY.created_date DESC;') ;
select SelectClause;
SET #query = SelectClause;
PREPARE stmt FROM #query;
EXECUTE stmt;
select stmt;
end if;
END
I tried a lot but not getting any problem. I also tried select clause to print the command at various places to not able to print it.
Please give me some solution.
There are my parameters that I am passing
v_mode='SearhByString'
v_SearchString='SURVEY_USER.username=chiragfanse'
It should return 48 rows but does not return anything.
BEGIN
DECLARE SelectClause VARCHAR(2000);
IF v_mode = 'SearchString' THEN
SET SelectClause = CONCAT('select SURVEY_USER.username,SURVEY.* from SURVEY, SURVEY_USER');
IF SearchString IS NOT NULL THEN
SET SelectClause = CONCAT(SelectClause, ' where ', SearchString);
END IF;
SET SelectClause = CONCAT(SelectClause, ' order by SURVEY.created_date DESC;');
SET #query = SelectClause;
PREPARE stmt FROM #query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END IF;
END
All declaration have to be at the begining.
Rename #SelectClause to SelectClause, because you are declaring this variable.
Check the usage of SET clauses. I have added one.
Have a look at prepared statements reference, it will help you to execute the query you built.
you have wrong concat functions. Try this.
if v_mode='SearchString' then
DECLARE #SelectClause varchar(2000);
SET #SelectClause =CONCAT(select (SURVEY_USER.username,SURVEY.*) from SURVEY, 'SURVEY_USER');
if SearchString is not null then
#SelectClause=CONCAT(#SelectClause, 'where' ,SearchString);
end if;
SET #SelectClause=#SelectClause
order by SURVEY.created_date DESC
execute(#SelectClause)
end if;
try this. let me know if you need anything else.

MySQL Pass table name to cursor select

I want the procedure to take parameter answertable and partid in the select statement,
but when i call it it doesn't replace the parameter answertable with the value
the call call updateTotalScores('quiz_participation', 'quiz_answer', 1)
returns the error: 1146 - Table 'quizdb.answertable' doesn't exist
passing the id works, but passing the table name doesn't
so how do i pass the table name to the select in
DECLARE cur1 CURSOR FOR SELECT SUM(`score`), SUM(`maxscore`) FROM answertable WHERE `idParticipation`=partid;
entire procedure:
DELIMITER $$
CREATE PROCEDURE updateTotalScores(IN participationtable CHAR(64), IN answertable CHAR(64), IN partid INT)
BEGIN
DECLARE done INTEGER DEFAULT 0;
DECLARE sscore INTEGER DEFAULT 0;
DECLARE smaxscore INTEGER DEFAULT 0;
DECLARE cur1 CURSOR FOR SELECT SUM(`score`), SUM(`maxscore`) FROM answertable WHERE `idParticipation`=partid;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
OPEN cur1;
REPEAT
FETCH cur1 INTO sscore, smaxscore;
UNTIL done = 1
END REPEAT;
CLOSE cur1;
UPDATE participationtable SET `score`=sscore, `maxscore`=smaxscore WHERE `idParticipation`=partid;
END $$
DELIMITER ;
For completeness
the table name cannot be passed to a MySql cursor, at least not yet
http://forge.mysql.com/worklog/task.php?id=3433
the answer from below (corrected a bit)
DELIMITER $$
CREATE PROCEDURE updateTotalScores(IN participation_table VARCHAR(45), IN answer_table VARCHAR(45), IN part_id INT)
BEGIN
SET #stmt_text=CONCAT("SELECT #score := SUM(`score`), #maxscore := SUM(`maxscore`) FROM ",
answer_table, " WHERE `idParticipation`=", part_id);
PREPARE stmt FROM #stmt_text;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
SET #stmt_text=CONCAT("UPDATE ", participation_table,
" SET `score`=?, `maxscore`=? WHERE `idParticipation`=", part_id);
PREPARE stmt FROM #stmt_text;
EXECUTE stmt USING #score, #maxscore;
DEALLOCATE PREPARE stmt;
END $$
I believe you cannot do it in this manner.
In order to achieve this, you should use Dynamic SQL.
Note that you cannot open a cursor using Dynamic SQL either. But in your case, there seems to be no need for a cursor.
If i understand your code correctly, you can just use user variables and probably achieve what you are trying to do using 2 Dynamically prepared statements.
SET #stmt_text=CONCAT("SELECT #score = SUM(`score`), #maxscore=SUM(`maxscore`) FROM ",
answertable, "WHERE `idParticipation`= ", partid);
PREPARE stmt FROM #stmt_text;
EXECUTE stmt USING #a;
And then you update the values using the below statement
SET #stmt_text=CONCAT("UPDATE", participationtable, " SET `score`=#score,
`maxscore`=#maxscore WHERE `idParticipation`=", partid);
PREPARE stmt FROM #stmt_text;
EXECUTE stmt USING #a;
DEALLOCATE PREPARE stmt;
Note: Please check the syntax. I cannot test it to verify it exactly but i hope you get the idea.

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.