在存储过程中过滤 CTE

Filtering a CTE in a Stored Procedure

我需要通过过程参数过滤 cte 数据 - 事实上,如果 @agentid 为 null 则给我所有数据,否则通过 @agentid 过滤数据。我尝试了很多方法,我在 cte 中使用了 case 并得到了错误,我使用了 if in(如果 @status 在 cte 之后)并且我得到了错误,我在 cte 中使用了 if 并得到了错误

此程序适用于分页和过滤数据,效果很好。

USE [HN_PRODUCTION]
GO

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[grid_data_pagination]  
    @status int  = null 
    , @offset int = 0 
    , @limit int = 2  
    , @agentid int = null 
    , @start_date date = null 
    , @end_date date = null                         
AS
BEGIN         
    IF  @status is  null  
    BEGIN       
            with cte as 
            (
                Select  FilePath  , ReceptionLocalTime , AgentID , FileDuration   , PhoneNumber , Indice   , Status  , ROW_NUMBER() over (  order by ID ) as RowNumber
                from dbo.V1_594                 
            )

    select FilePath as مسیر ,ReceptionLocalTime as زمان , FileDuration as مدت , PhoneNumber  as تلفن , Indice as اندیس , Status as وضعیت 
    from cte
    where cte.RowNumber > @limit * @offset and cte.RowNumber <= @limit * ( @offset + 1 )                                
    END
    ELSE 
    BEGIN
        with cte as 
        (
            Select  FilePath  , ReceptionLocalTime   , FileDuration   , PhoneNumber , Indice   , Status  , ROW_NUMBER() over (  order by ID ) as RowNumber
            from dbo.V1_594
            WHERE Status = @status 
        )

        select FilePath as مسیر ,ReceptionLocalTime as زمان , FileDuration as مدت , PhoneNumber  as تلفن , Indice as اندیس  
        from cte
        where cte.RowNumber > @limit * @offset and cte.RowNumber <= @limit * ( @offset + 1 ) ;
    END
END

如果包含您遇到的错误,我会很有帮助,但也许这会有所帮助。 如果我理解正确的话,你想过滤掉 CTE 的值吗?

您不需要 IF 状态语句。您可以在 where 子句中完成所有操作

ALTER PROCEDURE [dbo].[grid_data_pagination]  
    @status int  = null 
    , @offset int = 0 
    , @limit int = 2  
    , @agentid int = null 
    , @start_date date = null 
    , @end_date date = null                         
AS
BEGIN


    with cte as 
    (
        Select FilePath, ReceptionLocalTime, AgentID, FileDuration, PhoneNumber, Indice, Status, ROW_NUMBER() over (  order by ID ) as RowNumber
        from dbo.V1_594  
        WHERE (@agentid IS NULL OR AgentId = @agentid)
        AND (@status IS NULL OR Status = @status)
    )

    select FilePath as مسیر ,ReceptionLocalTime as زمان , FileDuration as مدت , PhoneNumber  as تلفن , Indice as اندیس  
    from cte
    where cte.RowNumber > @limit * @offset and cte.RowNumber <= @limit * ( @offset + 1 ) ;
END

希望对您有所帮助