0

我正在尝试使用 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'

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

4

1 回答 1

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
于 2012-10-07T08:57:54.993 回答