I have a SQL query running on SQL Server 2012 that needs to compare a bit value and return a string if that value is 1 and an empty string if it is zero.
Originally I had it as a CASE statement like this:
CASE WHEN myBit = 0 THEN
-- do other comparisons etc to build up the return string.
+'myString'
ELSE
-- do other comparisons etc to build up the return string.
'' END
The problem is that all of the code in ‘do other’ section is the same. All I want to do is append a string to the returned value if the bit is zero and nothing if it is 1.
So I refactored it to only have the common code once and then append to the string at the end like this:
-- do other comparisons etc to build up the return string. +
ISNULL(NULLIF(Cast(ISNULL(CAST(NULLIF(myBit, 0) AS NVARCHAR), 'myString') AS varchar),'0'),'')
However the above seems very messy not least because of the CAST statements required.
I’m looking for a clean and neat way of doing this but have run out of ideas – anyone have a better way of achieving this? Thanks.
You can also use
IIFandCONCATas you are on SQL Server 2012.IIFis a bit more concise thanCASE.CONCATmight be beneficial in that it casts non string types to strings automatically and concatenatingNULLis treated the same as concatenating an empty string.