2014-01-21 204 views
0

我試圖編寫一個函數,它使用列作爲參數。但是,它沒有工作。我想知道如何修復它。謝謝。sql函數使用列作爲參數

CREATE FUNCTION dbo.tempMedian(@SCORE INT) 
RETURNS @tempTable TABLE 
(
    onetcode VARCHAR(20), 
    SCORE INT 
) 
AS 
BEGIN 
    WITH median(onetcode, SCORE, RowNum, loc_total) AS 
    (
     SELECT onetcode, 
     @SCORE, 
     ROW_NUMBER() OVER (PARTITION BY onetcode ORDER BY @SCORE), --ORDER SCORE AND ASSIGN ROW NUMBER 
     COUNT(onetcode) OVER (PARTITION BY onetcode) --TOTAL NUMBER OF CASES 
     FROM t AS c 
) 

INSERT @tempTable 
SELECT onetcode, AVG(@SCORE) avgAGW 
FROM median 
WHERE RowNum BETWEEN (loc_total + 1)/2 AND (loc_total+ 2)/2 
GROUP BY onetcode 
    RETURN 
END; 
GO 
+0

什麼不起作用?你有錯誤嗎?還是沒有收到預期的結果?那麼結果應該是什麼? –

+0

爲了將列作爲變量,需要動態SQL。我不認爲你可以編寫一個使用動態SQL的函數。 –

回答

0

使用CASE語句

... 
ROW_NUMBER() OVER (
    PARTITION BY [onetcode] 
    ORDER BY 
    CASE @SCORE --Choose sorting column 
     WHEN 1 THEN [Column1] 
     WHEN 2 THEN [Column2] 
     ELSE  [Column3] 
    END 
) 
... 
0

這裏是最終的查詢,這對我的作品。感謝您的投入。

CREATE FUNCTION dbo.tempMedian(@col INT) 
RETURNS @tempTable TABLE 
(
    onetcode VARCHAR(50), 
    SCORE FLOAT 
) 
AS 
BEGIN 
    WITH median(onetcode, SCORE, RowNum, loc_total) AS 
(

    SELECT onetcode, 
    CASE @col 
     WHEN 1 THEN A 
     WHEN 2 THEN C 
     ELSE O 
    END, 
    ROW_NUMBER() OVER (PARTITION BY onetcode 
    ORDER BY 
     CASE @col --Choose sorting column 
      WHEN 1 THEN A 
      WHEN 2 THEN C 
      ELSE O 
     END), --ORDER SCORE AND ASSIGN ROW NUMBER 
    COUNT(onetcode) OVER (PARTITION BY onetcode) --TOTAL NUMBER OF CASES 
    FROM dbo.PCIInfoSingleScore131230AfterCleaning AS c 
) 

INSERT @tempTable 
SELECT onetcode, AVG(SCORE) AS median 
FROM median 
WHERE RowNum BETWEEN (loc_total + 1)/2 AND (loc_total+ 2)/2 
GROUP BY onetcode 
RETURN 
END; 
GO