我正在比较表中两行之间的数据,因为我想知道在哪些列中存在差异。因此,我编写了具有SQL Server XML功能的代码。
例如,我创建了一个包含FirstName,LastName和BirthDate的表。数据来自不同的来源。我想确保两个来源都为我提供相同的数据。如果不是这种情况,我将在结果中指出关注的列及其值
Id Source FirstName LastName Birthday
1 1 Toto Titi 2001-01-30
1 2 Totos Titi NULL
如您所见,我的生日列为空值。 *我的问题:如何将null值与xml中的数据进行比较。谢谢您的帮助
我的SQL代码:
CREATE TABLE dbo.MyTable
(
Id int,
Source int,
FirstName varchar(100),
LastName varchar(100),
Birthday Date
)
INSERT INTO dbo.MyTable
VALUES(1, 1, 'Toto', 'Titi', '2001/01/30'), (1, 2, 'Totos', 'Titi', NULL)
-------------------------
with A
as (
select Id, Source, (
Select *
from dbo.MyTable
where Id = pp.Id and Source = pp.Source
for xml auto, type) as X
from dbo.MyTable pp
)
--select * from A
, B
as (
select Id, Source
, X.query(
'for $f in dbo.MyTable/@*
return
<MyTable name="{ local-name($f) }" value="{ data($f) }" />
') as X2
from A
)
--select * from B
, C
as (
select B.Id as ID, B.Source
, norm.MyTable.value('@name', 'varchar(max)') as Name
, norm.MyTable.value('@value', 'varchar(max)') as Value
from B
cross apply B.X2.nodes('/MyTable') as norm(MyTable)
)
--select * from C
-- Result
select C1.Source, C1.Id, C1.Name as ColumnName, C1.Value as ColumnValue
from (select * from C) C1
full outer join (select * from C) C2
on C1.Name = c2.Name and C1.ID = C2.ID
where c1.Value <> c2.Value and C1.Name <> 'Source'
order by C1.ID, C1.Name
此代码的结果:
Source Id ColumnName ColumnValue
1 1 FirstName Toto
2 1 FirstName Totos
结果是,我想在ColumnName及其值中看到Birthday 这是我的预期结果:
Source Id ColumnName ColumnValue
1 1 Birthday 2001-01-30
1 1 FirstName Toto
1 2 Birthday NULL
2 1 FirstName Totos