mysql存储过程的语法

时间:2013-09-20 13:11:51

标签: mysql sql stored-procedures

我正在尝试在MySQL中创建一个存储过程,但它给我一个语法错误。

这是查询:

delimiter //
create procedure PostToTimeline (in txt text, in BY int, in FORR int)
begin if BY = FORR then
insert into posts (Body,UserID_BY,UserID_FOR) values(txt,BY,FORR);
else
insert into posts (Body,UserID_BY,UserID_FOR)
select txt, friends.UserID,friends.FriendID
from friends where friends.UserID = BY and friends.FriendID = FORR;
end//
delimiter;

有什么问题?

1 个答案:

答案 0 :(得分:1)

您不应该使用保留关键字。 BY是保留关键字。最好的解决方案是改变它而不是逃避它。

DELIMITER //
CREATE PROCEDURE PostToTimeline 
(
    IN txt TEXT, 
    IN BYParam INT, 
    IN FORR INT
)
BEGIN
    IF BYParam = FORR THEN
       INSERT INTO posts (Body, UserID_BY, UserID_FOR) 
       VALUES(txt, BYParam, FORR);
    ELSE
       INSERT INTO posts (Body, UserID_BY, UserID_FOR)
       SELECT txt, friends.UserID, friends.FriendID
       FROM friends 
       WHERE friends.UserID = BYParam AND
             friends.FriendID = FORR;
    END IF;
END//
DELIMITER ;

另一个问题是您的end if声明中没有if-else