根据参数制作更高效的SP

时间:2014-07-28 15:06:25

标签: sql sql-server-2008

我有以下存储过程,我想让它更有效率。当p_training不为null时,我会得到更多记录。

ALTER PROCEDURE [dbo].GetAssets
    @p_language VARVHAR(1) = 'E',
    @p_training BIT = NULL

AS
  IF (@p_training IS NOT NULL)
    SELECT Asset_Key AS CodeId,
           CASE WHEN @p_language = 'E' THEN HRMS_Desc_Eng
                WHEN @p_language = 'F' THEN HRMS_Desc_Fre
           END AS CodeName
    FROM Assets
    WHERE Asset_Type NOT IN ('C')
    ORDER BY CodeName
  ELSE
    SELECT Asset_Key AS CodeId,
           CASE WHEN @p_language = 'E' THEN HRMS_Desc_Eng
                WHEN @p_language = 'F' THEN HRMS_Desc_Fre
           END AS CodeName
    FROM Assets
    WHERE Asset_Type NOT IN ('C')
    AND (LocationId < 2000 OR LocationId > 2030)
    ORDER BY CodeName

如何才能提高效率或删除if语句?

感谢您的建议。

2 个答案:

答案 0 :(得分:1)

如果真正关注性能,最好的方法是将原始Stored Procedure拆分为2:

第一个SP:

CREATE PROCEDURE GetAssetsNotNull
@p_language VARVHAR(1) = 'E'

AS
SELECT Asset_Key AS CodeId,
       CASE WHEN @p_language = 'E' THEN HRMS_Desc_Eng
            WHEN @p_language = 'F' THEN HRMS_Desc_Fre
       END AS CodeName
FROM Assets
WHERE Asset_Type NOT IN ('C')
ORDER BY CodeName

第二个SP:

CREATE PROCEDURE GetAssetsNull
@p_language VARVHAR(1) = 'E'
AS
SELECT Asset_Key AS CodeId,
       CASE WHEN @p_language = 'E' THEN HRMS_Desc_Eng
            WHEN @p_language = 'F' THEN HRMS_Desc_Fre
       END AS CodeName
FROM Assets
WHERE Asset_Type NOT IN ('C')
AND (LocationId < 2000 OR LocationId > 2030)
ORDER BY CodeName

最后,您只能根据参数调用SP:

IF @p_training IS NOT NULL
EXEC GetAssetsNotNull
ELSE
EXEC GetAssetsNull

编辑:最后一部分可以在应用程序端或SP本身完成。

答案 1 :(得分:0)

我认为可以通过检查where子句中@p_training是否为空而不是使用IF

来减少代码重复
ALTER PROCEDURE [dbo].GetAssets
    @p_language VARVHAR(1) = 'E',
    @p_training BIT NULL    
AS
    SELECT Asset_Key AS CodeId,
           CASE WHEN @p_language = 'E' THEN HRMS_Desc_Eng
                WHEN @p_language = 'F' THEN HRMS_Desc_Fre
           END AS CodeName
    FROM Assets
    WHERE Asset_Type NOT IN ('C')
    AND (LocationId < 2000 OR LocationId > 2030 OR @p_training IS NOT NULL)
    ORDER BY CodeName

但这不会使查询更有效率。