• Phil Parkin (9/6/2012)


    mssqlsrv (9/6/2012)


    I think you can not use variable in order by clause.

    Variables are only allowed when ordering by an expression referencing a column name.

    Yeah you can. Just tried this and it works:

    declare @index int = 4

    select top 10 * from information_schema.COLUMNS

    order by (case @index when 4 then TABLE_SCHEMA else COLUMN_NAME end)

    Try this, Phil:

    DROP TABLE #Tester

    CREATE TABLE #Tester (col1 CHAR(1), col2 CHAR(1), col3 CHAR(1))

    INSERT INTO #Tester (col1, col2, col3)

    SELECT 'A', 'D', 'B' UNION ALL

    SELECT 'B', 'C', 'A' UNION ALL

    SELECT 'C', 'B', 'D' UNION ALL

    SELECT 'D', 'A', 'C'

    SELECT col1, col2, col3

    FROM #Tester

    ORDER BY col1

    -- Sort operator: col1 Ascending

    SELECT col1, col2, col3

    FROM #Tester

    ORDER BY 2

    -- Sort operator: col2 Ascending

    DECLARE @SortColumn INT

    SET @SortColumn = 3

    SELECT col1, col2, col3

    FROM #Tester

    ORDER BY @SortColumn

    -- The SELECT item identified by the ORDER BY number 1 contains a variable

    -- as part of the expression identifying a column position. Variables are

    -- only allowed when ordering by an expression referencing a column name.

    SELECT col1, col2, col3

    FROM #Tester

    ORDER BY (SELECT @SortColumn)

    -- @SortColumn is evaluated to a constant and optimised out: no sort operator

    DECLARE @Statement VARCHAR(8000)

    SET @Statement =

    'SELECT col1, col2, col3

    FROM #Tester

    ORDER BY '+CAST(@SortColumn AS CHAR(1))

    EXEC(@Statement)

    -- Sort operator: col3 Ascending

    “Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw

    For fast, accurate and documented assistance in answering your questions, please read this article.
    Understanding and using APPLY, (I) and (II) Paul White
    Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden