Answer: https://stackoverflow.com/a/24034862/1173155
I am testing a Stored procedure as follows:
DELIMITER $$
CREATE PROCEDURE `test1`(IN `tab_name` VARCHAR(40), IN `value_of` VARCHAR(40), OUT `the_id` INT(1))
BEGIN
SET @t1=CONCAT('
BEGIN
IF EXISTS (SELECT ',tab_name,'.id from ',tab_name,' where ',tab_name,'.',tab_name,' = ',value_of,')
THEN
select id into ',the_id,' from ',tab_name,' where ',tab_name,'.',tab_name,' = ',value_of,';
ELSE
insert into ',tab_name,' values (NULL,',value_of,');
END IF;');
PREPARE stmt3 FROM @t1;
EXECUTE stmt3;
DEALLOCATE PREPARE stmt3;
END $$
DELIMITER ;
Trying to select the id, or insert. I have a single row in the table, when I try and use this Procedure as is; it doesn't return anything.
The identifier for the value I want is the table name for simplicities sake. Have spent many hours and I'm at a loss.
Have tried everything, even now just thought adding the NULL, would work as the table has two values and I had forgotten to put it in only to realise I was trying it within the first if clause... IE, entering data to ensure that the first statement would be invoked
Thanks for any help
Update
Still having trouble with this. Trying to make it as simple as possible now.
I have a city table, with 1 record it in. Structure is like so city.city = 'Dublin'
Value and table name are the same. The follow select statement works when executed via phpMyAdmin
BEGIN
SET @t1= CONCAT("
SELECT id
FROM ",tab_name,"
WHERE ",tab_name," = '",value_of,"'
");
PREPARE stmt3 FROM @t1;
EXECUTE stmt3;
DEALLOCATE PREPARE stmt3;
END
Now I just need to ensure that if the select statement doesn't return anything, then insert the value and return the select statement.
This seems like such a simple problem, yet I can't find the solution anywhere
--
INSERT IGNORE is not good because it increments the ID regardless of inserting. Is there a work around for this because I could just use that then.
INSERT IGNORE... // Without increment?
SELECT ^ ....
Further Update
My procedure now looks like this (takes two VARCHAR parameters) and this is currently working. It doesn't increment the ID if the value already exists either which is simply fantastic.
BEGIN
SET @t1= CONCAT("INSERT INTO ",tab_name,"(",tab_name,")
SELECT '",city_name,"' FROM dual
WHERE NOT EXISTS (SELECT 1
FROM ",tab_name,"
WHERE ",tab_name," = '",city_name,"');
");
PREPARE stmt3 FROM @t1;
EXECUTE stmt3;
DEALLOCATE PREPARE stmt3;
END
All I want now is for a simple SELECT statement to return the id of the row with that city name. eg SELECT id FROM tab_name WHERE tab_name = 'city_name';
But adding this in causes an error :( Thanks if anyone has a solution to this ridiculous problem
DELIMITERimplies that's what you're doing)CREATE, or that it executes incorrectly? What looks a little suspect istab_name.tab_name, unless you always have a database with the same name as the inputtab_name(which seems unlikely)