samedi 7 février 2015

MySQL Subquery Returns Null In Stored Procedure, Works Fine In Query


I have a subquery in a MySQL Stored Procedure where the value returns null even though the data is clearly there. Pulling the subquery out and running it works fine. I've checked the parameter values going in and they are as expected. I can run a query in the procedure for all rows (SELECT * FROM) and the procedure will return the values in that table. As soon as I include the WHERE clause I get the null result.


Here is the offending subquery:



(SELECT id from SubStyles WHERE beer_style_name = beer_substyle_name AND style_id = (SELECT id from Styles WHERE style_name = beer_style_name))


Her is the procedure:



DELIMITER //
CREATE PROCEDURE insert_recipe
(
recipe_name nvarchar(150),
beer_style_name nvarchar(150),
beer_substyle_name nvarchar(150), -- Subtyle name
brewer_name nvarchar(200),
is_finalized bit,
original_gravity float,
final_gravity float,
abv float,
ibu float,
srm float,
boil_time int,
efficiency float,
pre_boil_volume float,
pre_boil_gravity float,
recipe_type_name nvarchar(20), -- Extract or All Grain
mash_type_name nvarchar(100), -- Infusion, Step, Decoction
competition_name nvarchar(200),
competition_placement nvarchar(100),
placement nvarchar(100)
)
BEGIN
DECLARE EXIT HANDLER FOR SQLEXCEPTION
BEGIN
ROLLBACK;
END;

START TRANSACTION;

IF competition_name IS NOT NULL AND (SELECT COUNT(*) FROM Competitions WHERE competition_name = competition_name LIMIT 1) < 1 THEN
INSERT INTO Competitions (competition_name) VALUES (competition_name);
END IF;

INSERT INTO Recipes (recipe_type_id, recipe_name,style_id, sub_style_id, is_finalized, brewer_full_name )
VALUES (
(SELECT id FROM RecipeTypes WHERE recipe_type_name = recipe_type_name and mash_type_id =
(SELECT id FROM MashTypes WHERE mash_type_name = mash_type_name LIMIT 1)),
recipe_name,
(SELECT id from Styles WHERE style_name = beer_style_name),
(SELECT id from SubStyles WHERE beer_style_name = beer_substyle_name AND style_id = (SELECT id from Styles WHERE style_name = beer_style_name)),
is_finalized, # is finalized
brewer_name); # brewers full name

IF competition_name = null THEN
SET @comp_id = null;
ELSE
SET @comp_id = (SELECT id FROM Competitions WHERE competition_name = competition_name);
END IF;

SET @recp_id = (SELECT id FROM Recipes WHERE recipe_name = recipe_name);
INSERT INTO RecipeSpecifications (recipe_id,original_gravity,
final_gravity, abv, ibu, srm, boil_time, efficiency, pre_boil_volume, pre_boil_gravity)
VALUES (@recp_id, original_gravity, final_gravity, abv,ibu, srm, boil_time, efficiency, pre_boil_volume,
pre_boil_gravity);

INSERT INTO CompetitionPlacements (recipe_id, competition_id, placement) VALUES (@recp_id, @comp_id, placement);
COMMIT;

END //
DELIMITER ;


I'm sure this is due to a gap in my knowledge of MySQL Stored Procedures but I can't seem to figure out what's going on.





Aucun commentaire:

Enregistrer un commentaire