views:

465

answers:

2

Is there a way to query SQL Server XML type so that for an element with xsi:nil="true", return null instead of default datetime value, which is 1900-01-01 00:00:00.000?

here is a code snippet

declare @data xml
set @data = 
 '<DOD xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
   xsi:nil="true" />'
select Value1 = @data.value('/DOD[1]', 'datetime'),
  Value2 = IsNull(@data.value('/DOD[1]', 'datetime'), 'NOT NULL?'),
  Value3 = nullif(@data.value('/DOD[1]', 'datetime'), '1900-01-01')

Value1 & Value2 both returns 1900-01-01 00:00:00.000. Is there a way to return a null, instead? without using nullif?

+1  A: 

The "default" datetime is caused by casting an empty string. So: tidy the string, then CAST

declare @data xml

set @data = 
        '<DOD   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
                        xsi:nil="true" />'

select
    Value1 = CAST(NULLIF(@data.value('/DOD[1]', 'varchar(30)'), '') AS datetime)
gbn
I think your approach looks better than what I was trying to do, which is ------ nullif(@data.value('string(/DOD[1]/@xsi:nil="true")', 'varchar(4)'), 'true')
Sung Meister
A: 

easy:

declare @data xml

set @data = 
        '<DOD   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
                        xsi:nil="true" />'

select
    Value1 = @data.value('(/DOD/text())[1]', 'varchar(30)')

best regards schacki