declare @T table
(
ID int,
Name varchar(10),
Age int,
City varchar(10),
Zip varchar(10)
)
insert into @T values
(1, 'Alex', 32, 'Miami', NULL),
(2, NULL, 24, NULL, NULL)
;with xmlnamespaces('http://www.w3.org/2001/XMLSchema-instance' as ns)
select ID,
(
select *
from @T as T2
where T1.ID = T2.ID
for xml path('row'), elements xsinil, type
).value('count(/row/*[@ns:nil = "true"])', 'int') as NullCount
from @T as T1
Resultat:
ID NullCount
----------- -----------
1 1
2 3
Opdatering:
Her er en bedre version. Tak til Martin Smith .
;with xmlnamespaces('http://www.w3.org/2001/XMLSchema-instance' as ns)
select ID,
(
select T1.*
for xml path('row'), elements xsinil, type
).value('count(/row/*[@ns:nil = "true"])', 'int') as NullCount
from @T as T1
Opdatering:
Og med et lidt hurtigere XQuery-udtryk.
;with xmlnamespaces('http://www.w3.org/2001/XMLSchema-instance' as ns)
select ID,
(
select T1.*
for xml path('row'), elements xsinil, type
).value('count(//*/@ns:nil)', 'int') as NullCount
from @T as T1