UNPIVOT will not return NULLs, but I need them in a comparison query. I am trying to avoid using ISNULL the following example (Because in the real sql there are over 100 fields.:
Select ID, theValue, column_name
From
(select ID,
ISNULL(CAST([TheColumnToCompare] AS VarChar(1000)), '') as TheColumnToCompare
from MyView
where The_Date = '04/30/2009'
) MA
UNPIVOT
(theValue FOR column_name IN
([TheColumnToCompare])
) AS unpvt
Any alternatives?
It's a real pain. You have to switch them out before the
UNPIVOT
, because there is no row produced forISNULL()
to operate on - code generation is your friend here.I have the problem on
PIVOT
as well. Missing rows turn intoNULL
, which you have to wrap inISNULL()
all the way across the row if missing values are the same as0.0
for example.Using dynamic SQL and COALESCE, I solved the problem like this:
I've found left outer joining the UNPIVOT result to the full list of fields, conveniently pulled from INFORMATION_SCHEMA, to be a practical answer to this problem in some contexts.
output looks like:
or, in SQLServer 2008 in shorter way:
To preserve NULLs, use CROSS JOIN ... CASE:
Instead of:
A text editor with column mode makes such queries easier to write. UltraEdit has it, so does Emacs. In Emacs it's called rectangular edit.
You might need to script it for 100 columns.
ISNULL is half the answer. Use NULLIF to translate back to NULL. E.g.
Here I use "0Null" as my intermediate value. You can use anything you like. However, you risk collision with user input if you choose something real-world like "Null". Garbage works fine "!@#34())0" but may be more confusing to future coders. I am sure you get the picture.