如何在MySQL中准备和执行多个语句?

时间:2019-02-11 22:10:53

标签: mysql stored-procedures appian

我在MySQL数据库上有一个存储过程,用于更新记录。根据输入,或者将小时添加到列中,或者减去小时到列中。我使用Appian智能服务进行存储过程调用此SP。我的问题是,如果尝试同时进行加和减(对于不同的行),则存储过程将不执行任何操作。它可以在我的流程模型中正常运行,但数据库未更新。如果我仅使用一个输入(加法或减法)运行PM,则它将相应地更新数据库。谁能告诉我我在SP中做错了什么? 注意:addAttendeeUsername和removeAttendeeUsername输入都是VARCHAR的字符串,以逗号分隔

    BEGIN

    DECLARE startTime datetime;
    DECLARE SQLStateCode varchar(5) DEFAULT '00000';
    DECLARE ErrorNumber int;
    DECLARE MessageText varchar(1000);

    -- insert / update

    set @sql = concat("UPDATE
      XCS_APP_CERTIFICATION
    SET
      COMPLETED_HOURS = COMPLETED_HOURS + ", courseHours , ",
      LAST_MODIFIED_BY = '", lastModifiedBy, "',
      LAST_MODIFIED_ON = NOW()
    WHERE
    XCS_APP_CERTIFICATION.CREATED_BY in (" , addAttendeeUsername , ") AND VALID_START_DATE <= '", offeringEndDateTime, "'
      AND GRACE_PER_END_DATE >= '", offeringEndDateTime,"' ");


    set @sql2 = concat("UPDATE
      XCS_APP_CERTIFICATION
    SET
      COMPLETED_HOURS = COMPLETED_HOURS - ", courseHours, ",
      LAST_MODIFIED_BY = '", lastModifiedBy, "',
      LAST_MODIFIED_ON = NOW()
    WHERE
      CREATED_BY IN (", removeAttendeeUsername, ")  AND VALID_START_DATE <= '", offeringEndDateTime, "'
      AND GRACE_PER_END_DATE >= '", offeringEndDateTime, "' ");

        PREPARE stmt FROM @sql;
        EXECUTE stmt;


        PREPARE stmt2 FROM @sql2;
        EXECUTE stmt2;

    set successFlag = 1;

    -- committing transaction
    COMMIT;

    END

1 个答案:

答案 0 :(得分:0)

目前还不清楚,因为您没有提供过程参数声明,但是我猜addAttendeeUsernameremoveAttendeeUsername是字符串。但是,您不要在SQL语法中使用引号。因此,它们将被解释为列名,无疑是找不到的。

您确实应该使用查询参数来组合输入变量,而不是将它们串联到SQL中。

set @sql = concat("UPDATE
  XCS_APP_CERTIFICATION
SET
  COMPLETED_HOURS = COMPLETED_HOURS + ?
  LAST_MODIFIED_BY = ?,
  LAST_MODIFIED_ON = NOW()
WHERE
XCS_APP_CERTIFICATION.CREATED_BY in (?) AND VALID_START_DATE <= ?
  AND GRACE_PER_END_DATE >= ? ");

SET @courseHours = courseHours, 
    @lastModifiedBy = lastModifiedBy,
    @addAttendeeUsername = addAttendeeUsername,
    @offeringEndDateTime = offeringEndDateTime;

PREPARE stmt FROM @sql;
EXECUTE stmt USING @courseHours, @lastModifiedBy,@addAttendeeUsername, 
  @offeringEndDateTime, @offeringEndDateTime;

EXECUTE时,必须使用会话变量(带有@符号的那种),而不是局部变量。