如何在mysql中使用相应的更新表传递值

时间:2016-11-10 06:18:57

标签: mysql

当我调用存储过程传入​​数据列表作为输入时:

IN pk VARCHAR(MAX)  = “11;12;13”
IN forenam varchar(MAX)= “Test1;Test2;Test3”
IN surnam varchar(MAX) = “Tst1;Tst2;Tst3”
IN bdate varchar(MAX) = “2016-01-02; 2016-01-04; 2016-01-03”
IN comm varchar(MAX) = “Comments1;comm2;comm3”
IN table_nam varchar(MAX)= “Name1”

它应该在一次调用SP

时更新名为“Name1”的表,如下所示
PK  forename    surname bdate   comments
11  Test1   Tst1    2016-01-02  Comments1
12  Test2   Tst2    2016-01-04  comm2
13  Test3   Tst3    2016-01-03  comm3`





CREATE DEFINER=`username`@`%` PROCEDURE `SP_UKFLMM_Update_multitable`(
IN pk int, 
IN forenam varchar(255), 
IN surnam varchar(255), IN bdate datetime,
IN comm varchar(1000), 
IN table_nam varchar(255))
BEGIN

if table_nam in ('UK_FLMM_demandData','UK_FLMM_Completed_demandData')
then 
UPDATE table_nam set forename=forenam,surname=surnam,birthDate=bdate,comments=comm where id=pk;

else if table_nam = 'UK_FLMM_sequenceData' then

UPDATE table_nam set comments=comm where id=pk;

end if;
end if;


END$$

DELIMITER

我已经尝试了上面的SP,但它一次只更新了一行。所以有人可以帮我解决这个问题。

1 个答案:

答案 0 :(得分:0)

尝试在where子句

中替换以下条件
WHERE LOCATE(REPLACE(id,';',','),pk) > 0;

希望这可以解决你的问题。

这将更新多条记录。但是会将'Comments1;comm2;comm3'更新为所有三个ID。

如果您需要更新如下

id comm
1  Comments1
2  comm2
3  comm3

然后这不起作用。

在这种情况下,您可以按照以下SP

进行操作
CREATE DEFINER=`username`@`%` PROCEDURE `SP_UKFLMM_Update_multitable`(
IN pk int, 
IN forenam varchar(255), 
IN surnam varchar(255), IN bdate datetime,
IN comm varchar(1000), 
IN table_nam varchar(255))
BEGIN

    DECLARE loopIncrement INT;
    DECLARE loopLimit INT;
    DECLARE nPK INT;
    DECLARE nForeName varchar(255);
    DECLARE nSurName varchar(255);
    DECLARE nBDate datetime;
    DECLARE nComm varchar(1000);

    SET loopLimit := 0;
    SET loopIncrement := 0;

    SET loopLimit := (LENGTH(pk) - LENGTH(REPLACE(pk,";",""))) + 1;

WHILE loopIncrement < loopLimit DO
    IF(loopIncrement = loopLimit - 1) THEN
        SET nPK := SUBSTRING_INDEX(pk,';',-1);
        SET nForeName := SUBSTRING_INDEX(forenam,';',-1);
        SET nSurName := SUBSTRING_INDEX(surnam,';',-1);
        SET nComm := SUBSTRING_INDEX(comm,';',-1);
        SET nBDate := SUBSTRING_INDEX(bdate,';',-1);
    ELSE    
        SET nPK := SUBSTRING_INDEX(pk,';',loopIncrement+1);
        SET nForeName := SUBSTRING_INDEX(forenam,';',loopIncrement+1);
        SET nSurName := SUBSTRING_INDEX(surnam,';',loopIncrement+1);
        SET nComm := SUBSTRING_INDEX(comm,';',loopIncrement+1);
        SET nBDate := SUBSTRING_INDEX(bdate,';',loopIncrement+1);
    END IF;

    if table_nam in ('UK_FLMM_demandData','UK_FLMM_Completed_demandData')
    then 
    UPDATE table_nam set forename=nForeName,surname=nSurName,birthDate=nBDate,comments=nComm where id=nPK;

    else if table_nam = 'UK_FLMM_sequenceData' then

    UPDATE table_nam set comments=nComm where id=nPK;

    loopIncrement++;

end if;
end if;

END WHILE;  


END$$

DELIMITER

注意:这只是一个示例SP,它实现了您的场景开始。如果您遇到任何问题,请改进它。