Trying to create an SQL Procedure but getting errors - mysql

I am trying to create a new SQL procedure and am getting a syntax error. I am not the greatest with SQL so I am sure I have an error in there somewhere. Can someone tell me what is wrong with it? thanks for any help.
create PROCEDURE `p_provider_get_distributors_by_sort`(varOffset INT(11), varSortName varchar(50), varSortDirection varchar(6))
BEGIN
SET #st := concat('(SELECT id FROM distributor WHERE status = "AC") ORDER BY 'varSortName, varSortDirection' LIMIT 100 OFFSET ', varOffset);
PREPARE stmt FROM #st;
EXECUTE stmt;
END //

You missed lot of things in your sp
first of all, You have to add prefix '#' with all your parameters
Secondly, You must have to declare your #st object

Related

Pass ANY string as a in parameter to a stored procedure in mysql (dynamic)

I am experiencing some trouble when I pass date-like strings to a input parameter of a stored procedure.
The table I try to modify has following columns:
create table localdevid.product_a(
INDX int PRIMARY KEY NOT NULL AUTO_INCREMENT,
ProdID int unsigned,
Assigned tinyint,
TesterID varchar(8),
tAss datetime);
Now I try to create a stored procedure:
use localdevid;
drop procedure if exists AssignNewDevID;
DELIMITER $$
use localdevid$$
CREATE PROCEDURE AssignNewDevID(in TableName varchar(255), in TesterName varchar(8), out DevID bigint(20))
BEGIN
#declare rightnow datetime;
set #t1=CONCAT("select SensorID into #localID from localdevid.",TableName," where ISNULL(Assigned) and INDX>1 order by INDX asc limit 1 for update");
prepare statement1 from #t1;
execute statement1;
deallocate prepare statement1;
set DevID=#localID;
set #t2=CONCAT("update localdevid.",TableName," set Assigned=4 where SensorID=",DevID);
prepare statement2 from #t2;
execute statement2;
deallocate prepare statement2;
set #t3=CONCAT("update localdevid.",TableName," set TesterID=",TesterName," where SensorID=",DevID);
prepare statement3 from #t3;
execute statement3;
deallocate prepare statement3;
commit;
END $$
DELIMITER ;
There were several issues, therefore I splitted it into the three statements to see where my problems might come from. I surely will later get it back into one statement back later on.
If I call the function the failure message changes:
call AssignNewDevID("product_a",'tester3',#id);
The script runs to statement2, this is executed successfully.
Statement3 drops Error Code 1054: "Unknown column 'tester3' in Field list.
I cannot understand why the parameter is interpreted as a field name.
It gets even stranger, if I pass a string as TesterName, which can be interpreted as a date or time.
In example, the TesterName are usually MAC-IDs, so the string is i.e. "00:08:01" (I transfer only the last 3 bytes of the MAC).
If I call it like this:
call AssignNewDevID("htpa32x32d",'00:08:01',#id);
I get error code: 1064: You have an error in your SQL syntax; check the manual...
What I am doing wrong here? Why can I concat TableName and DevID but not TesterName?
I don't see any difference here to the the other parameters.
Furthermore, I was not able to pass the current datetime to tAss. I did try the following:
declare rightnow datetime;
declare mydate varchar(20);
select DATE_FORMAT(now(),"%d.%m.%y") as mydate;
...
set #t4=CONCAT("update localdevid.",TableName," set tAss=",mydate," where SensorID=",DevID);
How can I pass basically NOW() to tAss?
OK, got it. Since I pass a string in TesterName I do need of course mark it between 'xxx' in this case.
So it works by
set #t3=CONCAT("update localdevid.",TableName," set TesterID='",TesterName,"' where SensorID=",DevID);
Same applies for the timestamp:
set #mydate=DATE_FORMAT(now(),"%d.%m.%y %h:%i:%S");
set #t4=CONCAT("update localdevid.",TableName," set tAss='",#mydate,"' where SensorID=",DevID);

MySQL Stored Procedure basics

This looks like a pretty rudimentary question but for someone who is new to MySQL, it has proven to be a tough nut to crack.
I've been trying to create a stored procedure in the MySQL and this is what I tried:
CREATE DEFINER=`root`#`localhost` PROCEDURE `test_procedure`(
IN dtst_nm varchar(42)
)
BEGIN
SELECT
COUNT(*)
FROM
data_hub.dtst_nm
;
END
When I run this, I get the error that dtst_nm doesn't exist. The exact error message is:
"Error Code: 1146. Table 'data_hub.dtst_nm' doesn't exist"
Clearly the variable is not getting resolved.
From what I gathered, the syntax seems to be right. What am I missing?
This is a Dynamic SQL problem. You cannot directly specify variables in place of table and column names. You will need to use string functions of create SQL query string. Then use Prepare with Execute to run the query.
Try:
DELIMITER $$
DROP PROCEDURE IF EXISTS `test_procedure` $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `test_procedure`(
IN `dtst_nm` varchar(42)
)
BEGIN
SET #s = CONCAT('SELECT COUNT(*) FROM ', dtst_nm );
PREPARE stmt FROM #s;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END $$
DELIMITER ;

CALL statement syntax error when passing multiple parameters mySql

I am running a query in MySQL 5.6.11. I have created a following stored procedure
DELIMITER $$
CREATE DEFINER=`root`#`localhost` PROCEDURE `digital_audio_test_detail`(IN temp VARCHAR(50), IN temp2 VARCHAR(50))
BEGIN
SET #temp_query = CONCAT('SELECT * FROM ',temp);
SET #final_query = CONCAT(#temp_query,'WHERE', temp,'.unit_test_result_id =',temp2);
PREPARE stmt FROM #final_query;
EXECUTE stmt;
END
When I call this procedure in my query page, I get syntax error at its CALL. This is how I execute my queries.
SELECT unit_test_result.*, #temp1 := unit_test.name, #temp2 := unit_test_result.id
FROM unit_test_result, unit_test
WHERE unit_test_result.test_run_id = 2
AND unit_test.id = unit_test_result.unit_test_id;
CALL digital_audio_test_detail(#temp1, #temp2);
I have to pass two parameters to the procedure. When I create a procedure with only first parameter and CALL it one parameter, it executes fine. But When I do with two parameters I get syntax error. Need help. Thanks
SET #final_query = CONCAT(#temp_query,'WHERE', temp,'.unit_test_result_id =',temp2);
The string you are building is not a valid query.
Add space before and after WHERE, as in
SET #final_query = CONCAT(#temp_query,' WHERE ', temp,'.unit_test_result_id =',temp2);

Dynamic table names in stored procedure function

I've written a stored procedure function to get a name from a table. The trouble is that I want the table name to be passed in as a parameter (there are several different tables I need to use this function with):
DELIMITER $$
CREATE DEFINER=`root`#`localhost` FUNCTION `getName`(tableName VARCHAR(50), myId INT(11)) RETURNS VARCHAR(50)
begin
DECLARE myName VARCHAR(50);
SELECT
'name' INTO myName
FROM
tableName
WHERE
id=myId;
RETURN myName;
end
This method has an error because it uses the variable name "tableName" instead of the actual value of the variable.
I can work around this problem in a procedure by using a CONCAT like this:
SET #GetName = CONCAT("
SELECT
'name'
FROM
",tableName,"
WHERE
id=",myId,";
");
PREPARE stmt FROM #GetName;
EXECUTE stmt;
...but, when I try to do this in a function I get a message saying:
Dynamic SQL is not allowed in stored function or trigger
I tried to use a procedure instead, but I couldn't get it to just return a value, like a function does.
So, can anyone see a way to get around this problem. It seems incredibly basic really.
If you want to buld a SQL statement using identifiers, then you need to use prepared statements; but prepared statements cannot be used in functions. So, you can create a stored procedure with OUT parameter -
CREATE PROCEDURE getName
(IN tableName VARCHAR(50), IN myId INT(11), OUT myName VARCHAR(50))
BEGIN
SET #GetName =
CONCAT('SELECT name INTO #var1 FROM ', tableName, ' WHERE id=', myId);
PREPARE stmt FROM #GetName;
EXECUTE stmt;
SET myName = #var1;
END
Using example -
SET #tableName = 'tbl';
SET #myId = 1005;
SET #name = NULL;
CALL getName(#tableName, #myId, #name);
SELECT #name;

IS there any way to pass variable while creating table in database?

I want to dynamically create table from my program with columns name and table name given by me through my program. so i want to pass my variable to the stored procedure but error occurs as i do like this
create procedure maketable
#name varchar(50),
#roll int
as
begin
create table new (#name, #roll)
end
error is as follow
Msg 102, Level 15, State 1, Procedure maketable, Line 7
Incorrect syntax near '#name'.
You're out of luck, MySQL stored procedures can not contain dynamic SQL, and the variable implementation can't be used how you're trying to use it.
Because you know all of the column information in your calling code, is there a specific reason you can't just issue the CREATE TABLE directly from your code? That would be the most straightforward way to get this done. (Mind you, having non-temporary tables spring into existence on demand is probably a bad, bad idea...)
Here's a start - this creates a table with one field so you should be able to finish it off:
DROP PROCEDURE IF EXISTS maketable;
delimiter //
CREATE PROCEDURE maketable (IN table_name varchar(50), IN field1Name varchar(50), IN field1Type varchar(50))
BEGIN
SET #s = CONCAT('CREATE TABLE ', table_name, '(', field1Name, ' ', field1Type, ')');
PREPARE stmt1 FROM #s;
EXECUTE stmt1;
END//
delimiter ;
CALL maketable('tst', 'id', 'INT');