Dynamic ORDER BY (ASC-DESC)

  • Dear People,

    I am looking for a simple piece of code i hope, for which i do not know the answer.

    I want to dynamically assign ASC or DESC to an ORDER BY clause in a SQL statement. I think it should be something like this:

    SELECT

    M_education.name,

    M_Education.xdate AS enddate

    ORDER BY Enddate

    declare @edu2 VARCHAR (3)

    if @edu_asc_desc = 0

    select @edu2 = 'ASC'

    select @edu2 as comment

    else

    select @edu2 = 'DESC'

    select @edu2 as comment

    end

    SELECT @EDU2

    GO

    Let me remind you, i just started sql server programming so i have to get used to the syntax. maybe it's a littlebit simple.

    who has a better idea ??

    deejay

  • Hi Deejay, an option is,

    SELECT

    M_education.name,

    M_Education.xdate AS enddate

    ORDER BY

    case @edu_asc_desc

    when 1 then Enddate

    else null

    end asc

    ,case @edu_asc_desc

    when 0 then Enddate

    else null

    end desc

    Thanks.

    Andy

    andyj93@hotmail.com

    .

Viewing 2 posts - 1 through 1 (of 1 total)

You must be logged in to reply to this topic. Login to reply