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
Резултат:
ID NullCount
----------- -----------
1 1
2 3
Актуализация:
Ето една по-добра версия. Благодарение на Мартин Смит .
;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
Актуализация:
И с малко по-бърз 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