无法在Concat中传递参数值选择Prepared语句

时间:2016-10-19 07:37:25

标签: mysql

我发现存储过程不会仅执行此部分:

          SET @sql 
          = CONCAT('SELECT TraineeID, ', @sql, ' 
                    from tbl_submit_coursefee c
                    where c.BatchID='BID'
                    group by c.TraineeID');

在where子句''引号中不允许和不带引号查询返回空,但如果我将参数值放在where子句中,则它可以正常工作。我真的很喜欢这个。

这是我准备好的陈述(工作正常):

SET @sql = NULL;    
SELECT
     GROUP_CONCAT(DISTINCT
     CONCAT ('MAX(IF(BillNo = ''', BillNo, ''', CRA, NULL)) AS `Inv.', BillNo, '`') 
         )  INTO @sql
    FROM tbl_submit_coursefee
    WHERE BatchID="ID-Welding/FMMTTC-01M/R8/01";

    SET @sql 
      = CONCAT('SELECT TraineeID, ', @sql, ' 
                from tbl_submit_coursefee c
                where c.BatchID="ID-Welding/FMMTTC-01M/R8/01"
                group by c.TraineeID');

    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;

将此语句放入存储过程(不工作)时:

DELIMITER @@
DROP PROCEDURE GetRetainment @@
CREATE PROCEDURE vtproject.GetRetainment
(IN `BID` VARCHAR(100))
BEGIN
    SET @sql = NULL;
    SELECT
        GROUP_CONCAT(DISTINCT
            CONCAT ('MAX(IF(BillNo = '', BillNo, '', CRA, NULL)) AS `Inv.', BillNo, '`') 
        )   INTO @sql
    FROM tbl_submit_coursefee
    WHERE BatchID=BID;

    SET @sql 
      = CONCAT('SELECT TraineeID, ', @sql, ' 
                from tbl_submit_coursefee c
                where c.BatchID='BID'
                group by c.TraineeID');

    PREPARE stmt FROM @sql;
    EXECUTE stmt;
    DEALLOCATE PREPARE stmt;
END @@ 
DELIMITER ; 

如果我在select @sql之前prepare stmt FROM @sql,则输出如下:

SELECT TraineeID, MAX(IF(BillNo = 1, CRA, NULL)) AS `Inv.1`,MAX(IF(BillNo = 2, CRA, NULL)) AS `Inv.2`,MAX(IF(BillNo = 3, CRA, NULL)) AS `Inv.3`,MAX(IF(BillNo = 4, CRA, NULL)) AS `Inv.4`,MAX(IF(BillNo = 5, CRA, NULL)) AS `Inv.5`,MAX(IF(BillNo = 6, CRA, NULL)) AS `Inv.6`,MAX(IF(BillNo = 7, CRA, NULL)) AS `Inv.7` from tbl_submit_coursefee c where c.BatchID=BID group by c.TraineeID

2 个答案:

答案 0 :(得分:1)

你需要逃避报价, 像这样:

SET @sql 
= CONCAT('SELECT TraineeID, ', @sql, ' 
from tbl_submit_coursefee c 
where c.BatchID=''',BID,''' 
group by c.TraineeID');

根据文档:http://dev.mysql.com/doc/refman/5.7/en/string-literals.html

答案 1 :(得分:1)

我自己以另一种方式找到了解决方案。

BEGIN
SET @sql = NULL;
SET @bid=BID;
SELECT
     GROUP_CONCAT(DISTINCT
        CONCAT ('MAX(IF(BillNo = ', BillNo, ', CRA, NULL)) AS `Inv.', BillNo, '`') 
     )  INTO @sql
FROM tbl_submit_coursefee
WHERE BatchID=@bid;

SET @sql 
  = CONCAT('SELECT TraineeID, ', @sql, ' 
            from tbl_submit_coursefee c
            where c.BatchID=@bid
            group by c.TraineeID');

PREPARE stmt FROM @sql;
EXECUTE stmt;
DEALLOCATE PREPARE stmt;
END