MYSQL:如何在存储过程中按参数值插入多行

时间:2017-09-21 05:37:18

标签: mysql

我用Google搜索,我找到了插入多行的解决方案:

CREATE PROCEDURE `usAddCostumeSet` 
    (argUserID BIGINT, argStarOID INT, argAcc1 INT, argAcc2 INT, 
     argBody INT, argHead INT, argNow DateTime)
BEGIN
    INSERT INTO COSTUME (UserID, StarOID, CostumeOID, CostumeTID, IsNewMark, CreateDate, FavDate) 
    VALUES (argUserID, argStarOID, argAcc1, argAcc1, true, argNow, null),
           (argUserID, argStarOID, argAcc2, argAcc2, true, argNow, null),
           (argUserID, argStarOID, argBody, argBody, true, argNow, null),
           (argUserID, argStarOID, argHead, argHead, true, argNow, null);

END

我想让它像下面那样

INSERT INTO COSTUME (UserID, StarOID, CostumeOID, CostumeTID, IsNewMark, CreateDate, FavDate)  
VALUES 
     if argAcc1 is not Zero (argUserID, argStarOID, argAcc1, argAcc1, true, argNow, null),
     if argAcc2 is not Zero (argUserID, argStarOID, argAcc2, argAcc2, true, argNow, null),
     if argBody is not Zero (argUserID, argStarOID, argBody, argBody, true, argNow, null),
     if argHead is not Zero (argUserID, argStarOID, argHead, argHead, true, argNow, null);

END

有一个简洁的解决方案吗?

2 个答案:

答案 0 :(得分:1)

你可以使用INSERT INTO ... SELECT

这样做
INSERT INTO COSTUME (UserID, StarOID, CostumeOID, 
                     CostumeTID, IsNewMark, CreateDate, FavDate) 
SELECT argUserID, argStarOID, 
  CASE WHEN argAcc1 <> 0 THEN argAcc1
       WHEN argAcc2 <> 0 THEN argAcc2
       WHEN argBody <> 0 THEN argBody
       WHEN argHead <> 0 THEN argHead
  END,
  CASE WHEN argAcc1 <> 0 THEN argAcc1
       WHEN argAcc2 <> 0 THEN argAcc2
       WHEN argBody <> 0 THEN argBody
       WHEN argHead <> 0 THEN argHead
  END,
  true, argNow, null

答案 1 :(得分:0)

暂时思考

我意识到一个解决方案。使用Union all

我不知道如何测量性能或危险,无论如何这里是代码。

INSERT INTO COSTUME SELECT argUserID, argStarOID, tempTbl.idx, tempTbl.idx, true, argNow, null FROM (SELECT argAcc1 as idx UNION ALL
SELECT argAcc2 UNION ALL
SELECT argHair UNION ALL
SELECt argBody) as tempTbl WHERE tempTbl.idx != 0;

但毕竟我决定使用Transaction和多个IF语句......

任何建议都将被授予......谢谢