order by a parameter

前端 未结 3 1667
一生所求
一生所求 2020-12-11 02:24

Hi i have a store procedure, where i do a select query. I want order this by an external parameter.

I post an minimal example:

CREATE PROCEDURE [dbo]         


        
3条回答
  •  挽巷
    挽巷 (楼主)
    2020-12-11 02:47

    You have 2 options, either use a CASE statement, or use dynamic sql

    This would be an example of the CASE statement

    DECLARE @Table TABLE(
            Col1 VARCHAR(10),
            Col2 VARCHAR(10)
    )
    
    DECLARE @OrderBy VARCHAR(100)
    
    SET @OrderBy = 'Col1'
    
    SELECT  *
    FROM    @Table
    ORDER BY 
            CASE
                WHEN @OrderBy = 'Col1' THEN Col1
                WHEN @OrderBy = 'Col2' THEN Col2
                ELSE Col1
            END
    

    And this would be and example of dynamic sql

    CREATE TABLE #Table (
            Col1 VARCHAR(10),
            Col2 VARCHAR(10)
    )
    
    DECLARE @OrderBy VARCHAR(100)
    
    SET @OrderBy = 'Col1'
    
    DECLARE @SqlString NVARCHAR(MAX)
    
    SELECT @SqlString = 'SELECT * FROM #Table ORDER BY ' + @OrderBy
    
    EXEC(@Sqlstring)
    
    DROP TABLE #Table
    

提交回复
热议问题