2

I have an integration type project where my select column often has this code:

select 
CASE MyColumn
    WHEN '' THEN '&' 
    ELSE MyColumn
END

Is there a simpler approach? Sort of like coalesce with nulls? I'm finding the query really hard to read, etc.

Thanks

1
  • see 'accepted' answer below. I actually didn't need to preserve the null, and the main goal afterall, was to simplify the query so it would be easier to read without repeating 'MyColumn' so many times. Commented Nov 16, 2013 at 0:26

4 Answers 4

2

I guess you can try something like this...

 COALESCE(NULLIF(MyColumn,''), '&')
Sign up to request clarification or add additional context in comments.

4 Comments

This isn't functionally equivalent... the original implementation would preserve a NULL value, this replaces NULL with '&'.
well spotted, ops @Vishal and me exactly the same answer :)
I guess in this case, CASE statement should do the job.
Thanks - I actually didn't need to preserve the NULL, but if I did, one of the other answers would do the trick... though remember, the initial goal was to simplify the select compared to a case when structure, and I'm not sure if any of the other answers simplifies it. This one does.
1

You could use COALESCE, following would check null and empty string from here -

COALESCE(NULLIF(MyColumn,''), '&')

2 Comments

This isn't functionally equivalent... the original implementation would preserve a NULL value, this replaces NULL with '&'.
That's true, don't see a way around the case then.
0

Following on from @Michael Fredrickson's comment

NULLIF(COALESCE(NULLIF(COALESCE(MyColumn,'###'),''), '&'),'###')

Replace ### with anyvalue you know won't appear in the field. Not sure it's easier to read than the case statement though.

Comments

0

This should work, and preserve nulls:

SELECT COALESCE(NULLIF(MyColumn, ''), NULLIF(MyColumn + '&', ''), MyColumn)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.