过滤存储过程中的CTE

时间:2015-01-10 12:44:20

标签: sql sql-server sql-server-2008 tsql

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

此过程适用于分页和过滤数据,并且工作正常。

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

1 个答案:

答案 0 :(得分:1)

我会帮助你包含你得到的错误,但也许这会有所帮助。 如果我正确理解了问题,您想过滤掉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

希望有所帮助