传递参数时过滤a,不传递参数时返回all

时间:2014-11-10 16:27:34

标签: sql sql-server sql-server-2012

如何在传递参数时从查询中过滤记录,并在参数具有空值时返回all。

SELECT nfv.Company_id, COUNT(1) as NegativeFeedback,SUM(allocated_score) as ScoreSum
FROM dbo.NegativeFeedbackView nfv
WHERE ISNULL(nfv.comp_nature_id,0) = @compNatureId 
GROUP BY nfv.Company_id

2 个答案:

答案 0 :(得分:1)

使用IF/ELSE

e.g。

IF @compNatureId IS NULL
BEGIN

    SELECT nfv.Company_id, COUNT(1) as NegativeFeedback,SUM(allocated_score) as ScoreSum
    FROM dbo.NegativeFeedbackView nfv
    WHERE ISNULL(nfv.comp_nature_id,0) = @compNatureId 
    GROUP BY nfv.Company_id

END
ELSE
BEGIN

    SELECT nfv.Company_id, COUNT(1) as NegativeFeedback,SUM(allocated_score) as ScoreSum
    FROM dbo.NegativeFeedbackView nfv
    GROUP BY nfv.Company_id

END

尝试将情境合并为一个查询:

SELECT nfv.Company_id, COUNT(1) as NegativeFeedback,SUM(allocated_score) as ScoreSum
FROM dbo.NegativeFeedbackView nfv
WHERE ISNULL(nfv.comp_nature_id,0) = @compNatureId 
OR @compNatureId IS NULL
GROUP BY nfv.Company_id

可能会产生次优计划,并且不能在comp_nature_id上使用任何索引(如果存在)。

答案 1 :(得分:0)

下面是一个示例proc,它采用可选参数进行过滤。

CREATE PROCEDURE USP_MyProc(@FilterParameter AS VARCHAR(100) = NULL)

BEGIN

SELECT nfv.Company_id, COUNT(1) as NegativeFeedback,SUM(allocated_score) as ScoreSum
FROM dbo.NegativeFeedbackView nfv

WHERE
(@compNatureId  IS NULL OR ISNULL(nfv.comp_nature_id,0)= @compNatureId )

GROUP BY nfv.Company_id

END