简体   繁体   English

在MySQL存储过程中使用选择

[英]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. 我已经在数据库中存储了过程,我需要查找一个表并交叉引用一个ID,然后使用返回的行将信息插入到另一个表中,但是我似乎无法使用查找中的信息插入到插入中。 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! 任何帮助将非常感激!

This won't insert the value of @UIDTOFB since you missed some ' . 由于您错过了一些' ,因此不会插入@UIDTOFB的值。 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());

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM