order by a parameter

前端 未结 3 1673
一生所求
一生所求 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 03:02

    Another option is to use an expression for the column that you want to sort by.

    DECLARE @OrderBy INT
    
    SET @OrderBy = 4
    
    SELECT     *
    FROM         MySourceTable
    ORDER BY COL_NAME(OBJECT_ID('MySourceTable'), @OrderBy )
    

    It is usually better to avoid dynamic sql if you can.

提交回复
热议问题