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 ;
Am I able to write a stored procedure with a parameter, which is the mysql query and the stored procedure returns the column names of the query?
For example I call the procedure:
call selector('select * from users')
And the procedure returns the column names.
It would be easy with information.schema but if I have a more complicated query and alias in it?
Found a solution
CREATE DEFINER=`admin`#`localhost` PROCEDURE `selector`(
IN `sql_query` VARCHAR(50))
LANGUAGE SQL
NOT DETERMINISTIC
CONTAINS SQL
SQL SECURITY DEFINER
COMMENT ''
BEGiN
drop table if exists tmp111;
SET #sql = concat('create table tmp111 as ', sql_query);
PREPARE stmt FROM #sql;
Execute stmt;
describe tmp111;
END
Then call it like:
call selector('select name as n, email as e from users')
I have a stored procedure with two varchar input parameters and one int output parameter. The idea is that I pass in the table name and an unique string, check the table to see if that string already exists in the table and return the id of that record if it does. Currently the sproc looks like:
BEGIN
SET #getID = CONCAT('SELECT `id` as id_Out FROM ',tablename_In,' WHERE `formSecret`=',formSecret_In);
PREPARE stmt FROM #getID;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END
If I pass in a number, everything works and I get a record id. If I pass in a full alpha-numeric string (which is what the unique ID's are), it fails, telling me that the column does not exist.
For example: call sp_GetRecordID(123456,'tbl_justsaythanks',#id_Out); will return a record ID just like I want.
But if I try a real id from the table that's a string...
`call sp_GetRecordID('fc66d9a82ba717e0931462370e64baff','tbl_justsaythanks',#id_Out);`
I get "Error Code: 1054. Unknown column 'fc66d9a82ba717e0931462370e64baff' in 'where clause'"
Since I'm new to MySQL, I'm not sure where I'm off on this - I suspect it has something to do with the application of tick marks in the query to designate the columns but I can't see it at the moment.
So, any help in pointing me the right way would be greatly appreciated.
Try a stored procedure like the following:
DROP PROCEDURE IF EXISTS `sp_GetRecordID`;
DELIMITER //
CREATE PROCEDURE `sp_GetRecordID`(
`tablename_In` VARCHAR(64),
`formSecret_In` VARCHAR(32),
OUT `id_Out` BIGINT UNSIGNED
)
BEGIN
SET #`query` := CONCAT('SELECT `id` INTO #`id_Out`
FROM ', `tablename_In` ,'
WHERE `formSecret` = \'', `formSecret_In`, '\'');
PREPARE `stmt` FROM #`query`;
EXECUTE `stmt`;
SET `id_Out` := #`id_Out`,
#`query` := NULL;
DEALLOCATE PREPARE `stmt`;
END//
DELIMITER ;
See db-fiddle example.
NOTE: Solution for this issue has been attached at the bottom. :)
5.6.17 - MySQL Community Server (GPL) Using MySQL Console
Trying to Test this procedure out in mysql console. It actually involves numerous fields which maybe searched against. Some values maybe defined as NULL.
I was having troubles with the query with an ERROR #1064 which involved a NULL value at line 1.
Here is the query and it breaks when I added the #P1 IS NULL test. I saw this somewhere but cannot for the life of my find it again...
SET #p0='46,51,52,1317,1318,1319,1320,1322,1323';
SET #p1='500-000';
CALL `searchCount2`(#p0, #p1);
DROP PROCEDURE IF EXISTS `searchCount2`//
CREATE PROCEDURE `searchCount2`(
IN _dealerIds varchar(100),
IN _dealerPhoneNumber varchar(10)
)
BEGIN
SET #query = CONCAT('SELECT count(cID)
FROM tblclassifieds c
JOIN tblphotos p
ON c.cmd5val=p.cClassCode
WHERE p.cpMain=1
AND c.cMarkedInappropriate=0
AND c.cBlacklisted=0
AND c.cEndDate>NOW()
AND (cType=29) OR (c.cType=27 OR c.cType=28)
AND c.cCompanyId IN (',_dealerIds,')
AND (("',_dealerPhoneNumber,'" is null) or (c.cPhoneNum="',_dealerPhoneNumber,'"));');
-- SELECT #query;
PREPARE stmt FROM #query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END //
Retested the Above using quotes.
Here is the example I have which works before I added the #P1 IS NULL, but as I mentioned this query is far from complete. There are numerous parameters to search against.
DROP PROCEDURE IF EXISTS `searchCount3`//
CREATE PROCEDURE `searchCount3`(
IN _dealerIds varchar(100),
IN _dealerPhoneNumber varchar(10)
)
BEGIN
SET #query = CONCAT('SELECT count(cID)
FROM tblclassifieds c
JOIN tblphotos p
ON c.cmd5val=p.cClassCode
WHERE p.cpMain=1
AND c.cMarkedInappropriate=0
AND c.cBlacklisted=0
AND c.cEndDate>NOW()
AND ((cType=29) OR (cType=27 OR cType=28))
AND c.cCompanyId IN (',_dealerIds,')
OR c.cPhoneNum=',_dealerPhoneNumber,';');
-- SELECT #query;
PREPARE stmt FROM #query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END //
SO what is my error with this NULL error? Is there another way I should implement this? How can I test it in MySQL?
Is Set #p1=NULL; valid?
Please disregard the horrible naming convention.
Thanks for any help. I have been struggling with this for too long.
Here is a print off of the query before it executes, SELECT #query:
SELECT count(cID)
FROM tblclassifieds c
JOIN tblphotos p
ON c.cmd5val=p.cClassCode
WHERE p.cpMain=1
AND c.cMarkedInappropriate=0
AND c.cBlacklisted=0
AND c.cEndDate>NOW()
AND (cType=29)
AND c.cCompanyId IN (46,51,52,1317,1318,1319,1320,1322,1323)
OR (cType=27 OR cType=28)
AND cCompanyId IN (46,51,52,1317,1318,1319,1320,1322,1323)
AND ((579-7775 is null) or (c.cPhoneNum=579-7775));
I copy and paste this query into sql console and I get results. But Execute fails! Why is this so? Error #1064.
SOLUTION:
I removed the parameter test for _dealerPhoneNumber IS NULL and replaced it with _dealerPhoneNumber = "". This has fixed the issue.
DROP PROCEDURE IF EXISTS `searchCount2`//
CREATE PROCEDURE `searchCount2`(
IN _dealerIds varchar(100),
IN _dealerPhoneNumber varchar(10)
)
BEGIN
SET #query = CONCAT('SELECT count(cID)
FROM tblclassifieds c
JOIN tblphotos p
ON c.cmd5val=p.cClassCode
WHERE p.cpMain=1
AND c.cMarkedInappropriate=0
AND c.cBlacklisted=0
AND c.cEndDate>NOW()
AND ((cType=29) AND cCompanyId IN (',_dealerIds,'))
OR ((cType=27 OR cType=28) AND cCompanyId IN (',_dealerIds,'))
AND (("',_dealerPhoneNumber,'" = "") or (c.cPhoneNum="',_dealerPhoneNumber,'"));');
-- SELECT #query;
PREPARE stmt FROM #query;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END //
try to define the parameters as null on the creation.
CREATE PROCEDURE `searchCount3`(
IN _dealerIds varchar(100) = NULL,
IN _dealerPhoneNumber varchar(10) = NULL
)
I had a similar issue. I was passing NULL to a MySQL stored procedure and getting this error message that I thought was obscure:
ERROR #1064 which involved a 'NULL' value at line 1.
I thought maybe passing NULL to stored procedures was not allowed, but it is allowed.
My issue was in the stored procedure, specifically:
I was dynamically generating an insert statement via a call to CONCAT, AND
i was not guarding against the presence of NULL, so i ended up with a quoted 'NULL' in my insert statement
By adding a condition in my string concatenation to account for NULL i was able to fix my issue
BEFORE
...
"more_info_link = '", more_info_link, "', ",
...
AFTER
IF(more_info_link IS NULL,
"more_info_link = NULL, ",
CONCAT("more_info_link = '", more_info_link, "', ")
),
What I want to do is,create a table in mysql by passing the table name as a parameter in the stored procedure.I'm using following code for stored procedure in mysql.
DELIMITER //
CREATE PROCEDURE createtable(IN tablename varchar(20))
BEGIN
SET #s=CONCAT('CREATE TABLE', tablename, '(month varchar(20))');
PREPARE stmt FROM #s;
EXECUTE stmt;
END //
and when i call it
CALL createtable('account');
I get the following error
You have an error in your SQL syntax; check the MySQL server version for the right syntax to us...
I don't know where I'm wrong..
You forgot the spaces before and after your table name. Try
DELIMITER //
CREATE PROCEDURE createtable(IN tablename varchar(20))
BEGIN
SET #s=CONCAT('CREATE TABLE ', tablename, ' (month varchar(20))');
PREPARE stmt FROM #s;
EXECUTE stmt;
END //