Convert!

  • How would you convert this into a series of if statements instead of using a case expression??
     
    select ProductID,ProductName,SupplierID,

    CASE WHEN ProductID=1 THEN 'P1'

     WHEN ProductID=2 THEN 'P2'

     WHEN ProductID=3 THEN 'P3'

     WHEN ProductID=4 THEN 'P4'

     WHEN ProductID=5 THEN 'P5'

     WHEN ProductID=6 THEN 'P1'

     WHEN ProductID=7 THEN 'P7'

     WHEN ProductID=8 THEN 'P8'

     WHEN ProductID=9 THEN 'P9'

     WHEN ProductID=10 THEN 'P10'

     WHEN ProductID=11 THEN 'P11'

     ELSE 'PN'

    END AS P

    FROM Northwind.dbo.Products

  • Basic syntax:

    if x

    begin

    --do what you want here

    end

    else if y

    begin

    --do what you want here

    end

    else

    begin

    --do what you want here

    end

    More importantly, what are you trying to accomplish?  As far as I know (and I have been known to be wrong), if statements aren't allowed within a SELECT.

  • Yeah, what do you mean a series of statements?

    what are you trying to accomplish?

  • i want to be able use any other syntax to produce the same results as this case expression but without using a case expression.

  • Why?

    Case was designed to do this.  Anything else would be much more complicated.

  • Because!  Case expressions can not be nested more than 10 levels if the query is against a linked server.

    Server: Msg 8180, Level 16, State 1, Line 1

    Statement(s) could not be prepared.

    Server: Msg 125, Level 15, State 1, Line 1

    Case expressions may only be nested to level 10.

  • select ProductID,ProductName,SupplierID,

    CASE WHEN ProductID < 11 THEN 'P' + CONVERT(varchar(2),ProductID)

     ELSE 'PN'

    END As NewP

    FROM Northwind.dbo.Products

  • Ah, now that's a bit more helpful.  Did a little MSDN searching and came up with the following:

    http://forums.microsoft.com/msdn/showpost.aspx?postid=260352&siteid=1

    I would agree with the poster - put the values into a temp table and do the case statement on that.

  • YOU GUYS/CHICKS TOTALLY ROCK!  Thanks!

Viewing 9 posts - 1 through 8 (of 8 total)

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