views:

25

answers:

1
DECLARE @xVar XML
SET @xVar = 
  '<book genre="security" publicationdate="2002" ISBN="0-7356-1588-2">
   <title>Writing Secure Code</title>
   <author>
      <firstname>Michael</firstname>
      <lastname>Howard</lastname>
      <age>25</age>
      <birthday>2010-05-17T00:00:00</birthday>
   </author>
   <author>
      <firstname></firstname>
      <lastname>LeBlanc</lastname>
      <age></age>
      <birthday></birthday>
   </author>
   <price>39.99</price>
   </book>'

SELECT nref.query('age') AS age
FROM @xVar.nodes('//author') AS authors(nref)

How can I check for an actual value in a node before parsing it into a column. When inserting into a normal table this code will insert 0 for the age when what I really need is null. Default values are inserted for any non text datatype like int or datetime(1/1/1900 inserted).

+2  A: 

You can use the built-in function NULLIF to do this:

SELECT NULLIF(nref.query('age'), 0) AS age
FROM ...

If the first term matches the second term, the function returns NULL. If not then it returns the first term.

Tom H.
+1: Though I'd use COALESCE instead
OMG Ponies
COALESCE is (roughly) equivalent to ISNULL, not NULLIF
Tom H.
NULLIF solves this problem. To use this means that for each non text column we have to know the non node return value int - 0; datetime - 01/01/1900. I never considered NULLIF and concentrated on a pure xquery solution. I'm really happy with this fix because it gets me out of a hole!!
Steven Chalk
Just thought another little teaser - what if the actual node value was one of the default empty node values say 01/01/1900 for the date. Happens I can get away with NULLIF but is there a better way of doing this?
Steven Chalk
I'm not sure what you mean. Do you mean, "<date=01/01/1900></date>"?
Tom H.
the query and value xquery functions always return a value even if the xml node is empty. So an empty datetime node will return a date of '01/01/1900' which is what will be inserted into relational column unless we do a check first - using NULLIF. My point is that this works great until we have a scenario where the default date just happened to be the actual date in the node! Using NULLIF would insert null into the relational table when what we actually wanted was the date.
Steven Chalk