views:

77

answers:

3

Please help me to convert the below statement:

CASE 
  WHEN TITLE IS NOT NULL THEN 'A'
  WHEN LOCAL_TITLE IS NOT NULL THEN 'B'
  END
AS COMBINED_TITLE

to something like this:

CASE 
  WHEN TITLE IS NOT NULL THEN COMBINED_TITLE=TITLE
  WHEN LOCAL_TITLE IS NOT NULL THEN COMBINED_TITLE=LOCAL_TITLE
  END
AS COMBINED_TITLE

Thanx in advance Greg

+2  A: 

ISNULL(TITLE, LOCAL_TITLE) AS COMBINED_TITLE

Chris Bednarski
Short and to the point. Like it.
Jonathan
Be wary though, if both TITLE and LOCAL_TITLE are NULL, this will set COMBINED_TITLE to NULL (although this may be want is required in this case)
Tim C
You are right Tim
Greg
So will the original case
Chris Bednarski
+2  A: 

I'm not sure what you mean, but if you're trying to set a variable, you would do this:

SELECT
    @CombinedTitle = CASE
        WHEN Title IS NOT NULL THEN Title
        WHEN Local_Title IS NOT NULL THEN Local_Title
    END
...

If you still want to create column Combined_Title but with values from the two title columns, you would do:

SELECT
    CASE
        WHEN Title IS NOT NULL THEN Title
        WHEN Local_Title IS NOT NULL THEN Local_Title
    END AS Combined_Title
...

Also see documentation on COALESCE, it even mentions that it is equivalent to a CASE statement just like yours (with the addition of ELSE NULL.)

Blixt
thanx Blixt, your second select is what I am after, unfortunately it does not work in SQL Server 2005...
Greg
Oops! It worked! Thanx a lot Blixt.
Greg
COALESCE is the way to go.
onedaywhen
+3  A: 

Are you trying to use it in an update statement? You could actually do away with the CASE statement in this instance

UPDATE
    <table>
SET
    COMBINED_TITLE = COALESCE(TITLE, LOCAL_TITLE, COMBINED_TITLE)

COALESCE will find the first NON-NULL value in the list

Tim C
+1: `COALESCE` is probably what Greg really wants.
Blixt
No Tim, I need it for reporting, thank you very much though
Greg