SitePoint Sponsor

User Tag List

Results 1 to 2 of 2
  1. #1
    Non-Member
    Join Date
    Feb 2001
    Posts
    136
    Mentioned
    0 Post(s)
    Tagged
    0 Thread(s)

    Using IF/THEN/ELSE in selects (MS SQL)

    Hello all,

    I have the following query :

    SELECT a,b,c FROM table WHERE a = 1

    This returns
    a => 1 (int)
    b => 0 (int)
    c => foobar (varchar)

    I would like to return a varchar value for b depending on its int value, for example

    if b = 0 return :
    a => 1 (int)
    b => There are no widgets (varchar)
    c => foobar (varchar)

    if b = 1 return :
    a => 1 (int)
    b => There is one widget (varchar)
    c => foobar (varchar)

    if b > 1 return :
    a => 1 (int)
    b => There are loads of widgets (varchar)
    c => foobar (varchar)

    I assume this can be done through some sort of IF/THEN/ELSE syntax but I am at a loss to finding a solution, so I would appreciate any guidance.

  2. #2
    SitePoint Guru
    Join Date
    Jan 2004
    Location
    Uppsala, sverige
    Posts
    697
    Mentioned
    2 Post(s)
    Tagged
    1 Thread(s)
    Code:
    select a , 
       case when b = 0 then 'No widgets'
              when b = 1 then 'One widget'
              else 'Many widgets' end as widgets,
       c
    from t
    where a = 1


Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •