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
Wynik:
ID NullCount
----------- -----------
1 1
2 3
Aktualizacja:
Oto lepsza wersja. Podziękowania dla Martina Smitha .
;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
Aktualizacja:
I z nieco szybszym wyrażeniem XQuery.
;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