2016-08-26 65 views
4

我正在嘗試創建我認爲是在列名稱的參數中調用的相當簡單的過程。無法通過子查詢在Mysql過程中傳遞參數

這是我創造的過程:

CREATE DEFINER=`root`@`%` PROCEDURE `test`(in col varchar(225)) 
BEGIN 
-- Column of Averages 
DROP temporary TABLE IF EXISTS temp; 

CREATE temporary TABLE IF NOT EXISTS temp AS 
    SELECT col, 
     Round(Avg(bcount), 0) AS `Average # of Loans` 
    FROM (SELECT col, 
       Count(borrower) AS bcount 
      FROM whatif_dataset 
      WHERE loan_lienposition = 'first' 
      GROUP BY col, 
        Month(Str_to_date(status_fundingdate, '%m/%d/%Y')), 
        Year(Str_to_date(status_fundingdate, '%m/%d/%Y')))AS dt 
    GROUP BY col; 

END 

然而,當我打電話的過程我只得到一個記錄,即:

Col    Average # of Loans 
'Passed Parameter' 757 

它就像參數沒有被傳遞在我看來,通過正確。 MYSQL中是否存在一些限制,不允許我這樣做?

當我運行與具體列名相同的查詢currentprocessor這是期望的結果:

currentprocessor Average # of Loans 
    proc1    20 
    proc2    12 
    proc3    8 
    proc4    22 
    proc5    24 
+0

你是什麼期待?您可能需要一個準備好的聲明,檢查此:http://stackoverflow.com/questions/11699027/dynamic-column-name-selection-in-mysql –

+0

謝謝,我用一個準備好的聲明,以獲得所需的結果 –

+0

不錯,看起來不錯。 –

回答

2

我能得到通過使用準備好的聲明中修正

CREATE DEFINER=`root`@`%` PROCEDURE `test`(in col varchar(225)) 
BEGIN 
-- Column of Averages 
DROP temporary TABLE IF EXISTS temp; 


SET @sql= CONCAT('SELECT ', col,',', 
     'Round(Avg(bcount), 0) AS `Average # of Loans` 
    FROM (SELECT ', col,', 
       Count(borrower) AS bcount 
      FROM whatif_dataset 
      WHERE loan_lienposition = ''first'' 
      GROUP BY ', col,', 
        Month(Str_to_date(status_fundingdate, "%m/%d/%Y")), 
        Year(Str_to_date(status_fundingdate, "%m/%d/%Y")))AS dt 
    GROUP BY ', col); 

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

END