确定在存储过程中的Select语句中使用哪个参数

时间:2014-05-29 19:15:35

标签: sql-server-2008

我有一个存储过程返回一个公共查询,我需要在几个函数中调用它,但有些函数可能通过句点ID或其他人通过Header Id调用它,到目前为止我想知道如何确定什么参数为了正确地检索数据,我实现了类似的东西。

CREATE PROCEDURE dbo.GetTFDRecordInfo
    @PeriodId int = null,
    @HeaderId int  = null
AS
BEGIN

    SELECT
        -- I have a lot more fields and joins here, that's why I need to get the statement in a single call through either period id or header id 
        *   
        From NT_CSRTNVPeriodInfo t

        -- how can I make possible something like shown above, can I use a "Case When"?
        Where (             
                /*
                if @PeriodId is null 
                    Where t.HeaderId = @HeaderId

                if @HeaderId is null
                    Where t.PeriodId = @PeriodId
                */
            )    
END
GO

-- swtich between params
Exec NT_CSRTNVPeriodInfo null, 2654
Exec NT_CSRTNVPeriodInfo 196, null

1 个答案:

答案 0 :(得分:1)

这就是答案:

CREATE PROCEDURE dbo.GetTFDRecordInfo
    @PeriodId int = null,
    @HeaderId int  = null
AS
BEGIN

    SELECT
        -- I have a lot more fields and joins here, that's why I need to get the statement in a single call through either period id or header id 
        *   
        From NT_CSRTNVPeriodInfo t

        -- how can I make possible something like shown above, can I use a "Case When"?
        Where ((@PeriodId IS NULL) or (t.PeriodId = @PeriodId))
        And   ((@HeaderId IS NULL) or (t.HeaderId = @HeaderId))
END
GO

你必须使用条件OR来检查NULL,如果设置了param,则检查第二个条件,否则,程序将始终认为该语句为真并转到下一个。