T-SQL Conditional Order By

后端 未结 5 588
闹比i
闹比i 2020-12-03 00:21

I am trying to write a stored procedure that returns a list of object with the sort order and sort direction selected by the user and passed in as sql parameters.

Le

5条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-12-03 01:24

    I stumbled on this when I was trying to do a similar thing, however the select statement I was creating includes a rather large and ugly string concatenation which severely limited my ability to use a dynamic SQL approach. If you have simple search cases, this is a decent solution.

    That being said, another way to do this in SQL server specifically is with a table variable. This requires more overhead and complexity but it also gives you a lot of flexibility.

    DECLARE @RawProducts TABLE (
        product_id int, 
        name varchar(50), 
        value int, 
        created_date datetime
    )
    INSERT INTO @RawProducts
    SELECT * FROM [Product]
    
    IF @sortOrder = 'name' AND @sortDir = 'asc' BEGIN
        SELECT * FROM @RawProducts
        ORDER BY [name] ASC
    END
    
    IF @sortOrder = 'name' AND @sortDir = 'desc' BEGIN
        SELECT * FROM @RawProducts
        ORDER BY [name] desc
    END
    
    IF @sortOrder = 'created_date' AND @sortDir = 'asc' BEGIN
        SELECT * FROM @RawProducts
        ORDER BY [created_date] ASC
    END
    
    IF @sortOrder = 'created_date' AND @sortDir = 'desc' BEGIN
        SELECT * FROM @RawProducts
        ORDER BY [created_date] desc
    END
    

    One drawback to this methodology is that you will need to add a case block for each and every case you want to order by but you would have to do that with any solution that does not involve dynamic SQL.

    The only time I would recommend this method is if you have a relatively small data set and you have easy to discern search cases.

提交回复
热议问题