Results 1 to 4 of 4
  1. #1
    Join Date
    Jul 2009
    Posts
    8

    Unanswered: use of an IF statement in SQL Server or something similar

    I have a table with the following Fields:

    ID
    First Name
    Last Name
    Nickname

    what I want to achieve is the following;

    I have ten records in this table. All ten records have First and Last Names, and two of the ten records also have nicknames (meaning eight of them are NULL).

    now I want to develop a query where, with an outputted field, where if the nickname is NOT NULL, then the output field (in the query) shows their first and last name. HOWEVER, if a record has a nickname, then in that same outputted field, the nickname is displayed instead of the first and last name.

    I know it sounds very long winded, but I am in some serious need of help with this issue. how can I resolve this?

    help would be much appreciated

  2. #2
    Join Date
    Jun 2009
    Location
    CA, USA
    Posts
    59
    If NickName is null
    begin
    select fname, lname from table
    end
    else
    select nickname from table
    MohammedU
    SQL Server MVP

  3. #3
    Join Date
    Nov 2003
    Posts
    2,933
    Provided Answers: 12
    Code:
    SELECT coalesce(nickname, firstname + ' ' + lastname)
    FROM the_table;

  4. #4
    Join Date
    Aug 2009
    Posts
    16
    The coalesce statement above is probably the best solution since you are dealing with NULL values. You other option is to use a CASE statement if you are dealing with multiple values/checks.

    SELECT
    CASE t.field_name
    WHEN 'check value 1' THEN exp1
    WHEN 'check value 2' THEN exp2
    ELSE exp3
    END as Exp
    FROM your_table t

Posting Permissions

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