使用CTE从存储过程运行时,Query提供未排序的结果集

时间:2012-10-07 08:12:13

标签: stored-procedures sql-server-2008-r2 common-table-expression row-number

我正在尝试使用CTE创建分页查询。当我从Microsoft SQL Server Management Studio查询编辑器执行它时,它工作正常。结果集完全按照我的要求排序。但是当我为存储过程修改它时,它会给我一个未排序的结果,我不知道为什么。

这是我的查询,

with items as
(
select ROW_NUMBER() over (order by create_time desc) number
    , i.item_name item_name
    , i.create_time create_time
    , c.category_name category_name
    , i.category_id category_id
from cb_item i, cb_category c
where i.category_id = c.category_id
and c.category_id = '4E5248FE-05DD-4D01-ABBB-80C6E3BA5CDA' 
)
select item_name
, create_time
, category_name
, category_id
from items
where number between 1 and 25

这是存储过程版本,

    create procedure ItemPage @category_id uniqueidentifier
    , @from int
    , @to int
    , @sortby nvarchar(50)
    as
    begin
    with items as
    (
    select ROW_NUMBER() over (order by @sortby) number
        , i.item_name item_name
        , i.create_time create_time
        , c.category_name category_name
        , i.category_id category_id
    from cb_item i, cb_category c
    where i.category_id = c.category_id
    and c.category_id = @category_id 
    )
    select item_name
    , create_time
    , category_name
    , category_id
    from items
    where number between @from and @to
    end


exec itempage '4E5248FE-05DD-4D01-ABBB-80C6E3BA5CDA' , 1, 25, 'create_time desc'

第一个给我排序结果,但程序给了我未分类的结果。我不知道为什么?

1 个答案:

答案 0 :(得分:0)

您必须按顺序使用Case,您可以在其中检查传递的值,因此可以按行排序。

您的查询应该是这样的:

 create procedure ItemPage @category_id uniqueidentifier
        , @from int
        , @to int
        , @sortby nvarchar(50)
        as
        begin
        with items as
        (
        select ROW_NUMBER() over (order by
                                    CASE @sortby
                                    WHEN 'create_time desc' THEN  create_time -- Here, I assume passed @sortby value is create_time , otherwise you can mapped with passed value
                                    END
                                    DESC,
                                    CASE @sortby
                                    WHEN 'create_time asc' THEN  create_time -- Here, I assume passed @sortby value is create_time , otherwise you can mapped with passed value
                                    END
                                    ASC
                                    ) number
            , i.item_name item_name
            , i.create_time create_time
            , c.category_name category_name
            , i.category_id category_id
        from cb_item i, cb_category c
        where i.category_id = c.category_id
        and c.category_id = @category_id 
        )
        select item_name
        , create_time
        , category_name
        , category_id
        from items
        where number between @from and @to
        end