MySQL - 存储过程中的动态SQL

时间:2010-06-04 12:34:26

标签: sql mysql stored-procedures dynamic

请参阅下面的InsertHelpQuestion2程序。

DROP PROCEDURE InsertHelpQuestion2;
CREATE PROCEDURE InsertHelpQuestion2(user_id char(50),scenerio_id char(50),component_id char(50))
BEGIN
    DECLARE uu_id char(50);
    SELECT BinToUUID(NewUUID()) INTO uu_id from helpquestion LIMIT 1;
    SET @fields_part = 'INSERT INTO helpquestion(HelpQuestionKey,UserKey';
    SET @values_part = CONCAT(' VALUES(UUIDToBin(\"', uu_id, '\"), UUIDToBin(\"', user_id, '\")');
    IF (scenerio_id) THEN
        SET @fields_part = CONCAT(@fields_part, ', ScenarioKey');
        SET @values_part = CONCAT(@values_part, ', UUIDToBin("', scenerio_id, '")');
    END IF;
    IF (component_id) THEN
        SET @fields_part = CONCAT(@fields_part, ', ComponentKey');
        SET @values_part = CONCAT(@values_part, ', UUIDToBin("', component_id, '")');
    END IF;
    SET @query_full  = CONCAT(@fields_part , @values_part, ';');
    PREPARE STMT FROM @query_full;
    EXECUTE STMT;
END

它有3个参数user_id,scenerio_id,component_id所有都是外键。

NewUUID(),UUIDToBin是存储函数。

由于字段有外部引用,我需要在过程中编写动态sql,以便以下调用工作

CALL InsertHelpQuestion2('F70724DC-AC0D-102D-9C16-00163EEDFCFC', '0F69476A-ABF2-102D-9C16-00163EEDFCFC', '06FFEE04-1FD9-11DF-9B60-001F16F664A9');

CALL InsertHelpQuestion2('F70724DC-AC0D-102D-9C16-00163EEDFCFC', '0F69476A-ABF2-102D-9C16-00163EEDFCFC', '');

CALL InsertHelpQuestion2('F70724DC-AC0D-102D-9C16-00163EEDFCFC', '', '');

但第一次打电话

CALL InsertHelpQuestion2('F70724DC-AC0D-102D-9C16-00163EEDFCFC', '0F69476A-ABF2-102D-9C16-00163EEDFCFC', '06FFEE04-1FD9-11DF-9B60-001F16F664A9');

发生以下错误

[Err] 1064 - You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'VALUES(UUIDToBin("69490F3A-6FD3-11DF-964F-F4CE462E9D80"), UUIDToBin("F70724DC-AC' at line 1

字符串连接有什么错误吗?

2 个答案:

答案 0 :(得分:1)

使用print @query_full查看您尝试执行的查询。您可以在单独的窗口中复制/粘贴它以进行调试。

一个明显的错误似乎是转义序列。

select '\"'
->
\"

答案 1 :(得分:1)

看起来你可能需要一个右括号。

SET @query_full = CONCAT(@ field_part,@ value_part,';');