Using selects within MySQL Stored Procedures

I have stored procedure in my database and i need to look up a table and cross reference an id, then using the returned row i need to insert information into another table, but i cant seem to use the infomation from the lookup into the insert. This is what i have..

BEGIN
#Routine body goes here...
SET @UID = uid;
SET @UIDTOFB = uid_to;

SET @SQLTEST = CONCAT('SELECT users.user_auto_id FROM users WHERE users.user_fb_uid=     @UIDTOFB LIMIT 1');
PREPARE sqlcmd from @SQLTEST;
EXECUTE sqlcmd;

INSERT INTO challenges(challenge_from_uid, challenge_to_uid, challenge_dateadded) VALUES(@UID, @SQLTEST.users.user_auto_id, now());

SET @LASTID = LAST_INSERT_ID();
SELECT @LASTID as id;

END

any help would be much appreciated!

Answers


This won't insert the value of @UIDTOFB since you missed some '. It takes this whole statement as one string and therefore the statement fails.

SET @SQLTEST = CONCAT('SELECT users.user_auto_id FROM users WHERE users.user_fb_uid=     @UIDTOFB LIMIT 1');
PREPARE sqlcmd from @SQLTEST;
EXECUTE sqlcmd;

Anyway I'd recommend you use parameters like this:

PREPARE sqlcmd from 'SELECT users.user_auto_id FROM users WHERE users.user_fb_uid= ? LIMIT 1';
EXECUTE sqlcmd USING @UIDTOFB;

You can read more about it here in the manual.

UPDATE: Now I get, what you want to do. Do it simply like this:

SELECT @anyVariable:=users.user_auto_id FROM users WHERE users.user_fb_uid= @UIDTOFB LIMIT 1;
INSERT INTO challenges(challenge_from_uid, challenge_to_uid, challenge_dateadded) VALUES(@UID, @anyVariable, now());

Need Your Help

How to make simple web dialog for web page

java javascript webpage

I'm new in the web programing. I'm making a web side and I wan to use lots of web dialogs like the ones in tweeter or fb. They are not pop-up windows and I guess can't be blocked by the browser. I ...