按条款动态订购

时间:2014-07-01 04:49:20

标签: sql sorting

我在下面的查询 -

中遇到了动态订单条款
        DECLARE @employee TABLE
        ( 
            ID INT IDENTITY(1,1)
            ,Name VARCHAR(50)
            ,Gender VARCHAR(20)
            ,DOB DATETIME
            ,TotProjects INT
        )


        INSERT INTO @employee
        (   
            Name
            ,Gender 
            ,DOB 
            ,TotProjects
        )
        VALUES 
        ('Mike', 'Male', '07/26/1986', 3)
        ,('Neil' , 'Male', '02/21/1990', 2)
        ,('Jessica' ,'FeMale','04/15/1988', 9)
        ,('Tony','Male','03/18/1987', 6)
        ,('Adam','Male','01/16/1983', 12)


        DECLARE @searchCol VARCHAR(50) = 'PROJECTS' 
        DECLARE @direction VARCHAR(5) = 'ASC'   

        SELECT *
        FROM @employee
        ORDER BY 
                CASE WHEN @direction = 'DESC'
                THEN
                CASE 
                    WHEN @searchCol = 'NAME' THEN Name 
                    WHEN @searchCol = 'GENDER' THEN Gender
                    WHEN @searchCol = 'DOB' THEN CAST (DOB AS VARCHAR(20)) 
                    WHEN @searchCol = 'PROJECTS' THEN ABS(TotProjects)
                END 
            END DESC,
            CASE WHEN @direction = 'ASC'
                THEN
                CASE 
                    WHEN @searchCol = 'NAME' THEN Name 
                    WHEN @searchCol = 'GENDER' THEN Gender
                    WHEN @searchCol = 'DOB' THEN CAST (DOB AS VARCHAR(20)) 
                    WHEN @searchCol = 'PROJECTS' THEN CAST(TotProjects AS VARCHAR(20))
                END
            END ASC



        --- Ends Here -----

所以在上面的查询中,我从一个名为@direction的变量获取Order By Direction,我将传递变量 - @searchCol来说明我的哪个列要进行排序。

现在,如果我传递 - “名称”或“性别”,它的排序就好了,因为两者都是VARCHAR列,但如果我想排序“项目”或“DOB”,它不会以正确的方式排序。 (可能是它的ascii值)。当我通过方向 - @direction - “ASC”和@searchCol - “项目”时,它给出了奇怪的结果。基本上它不基于“Projects”和“DOB”进行排序,因为它们分别是Numeric和Datetime字段。

请你详细说明。

1 个答案:

答案 0 :(得分:1)

我会以不同的方式实现动态排序。我相信通过这样做,数据库引擎将能够更有效地使用索引(前提是你已经得到它们)

 SELECT *
    FROM @employee
    ORDER BY 
    CASE WHEN @direction = 'DESC' AND @searchCol = 'NAME' THEN Name ELSE ' ' END DESC,
    CASE WHEN @direction = 'DESC' AND @searchCol = 'GENDER' THEN Gender ELSE ' ' END DESC,
    CASE WHEN @direction = 'DESC' AND @searchCol = 'DOB' THEN DOB ELSE CAST(0 AS DATE) END DESC,
    CASE WHEN @direction = 'DESC' AND @searchCol = 'PROJECTS' THEN TotProjects ELSE 0 END DESC,
    CASE WHEN @direction = 'ASC' AND @searchCol = 'NAME' THEN Name ELSE ' ' END,
    CASE WHEN @direction = 'ASC' AND @searchCol = 'GENDER' THEN Gender ELSE ' ' END,
    CASE WHEN @direction = 'ASC' AND @searchCol = 'DOB' THEN DOB ELSE CAST(0 AS DATE) END,
    CASE WHEN @direction = 'ASC' AND @searchCol = 'PROJECTS' THEN TotProjects ELSE 0 END