查找两个数据集之间的数据差异

 

Declare @vSQL varchar(max)
Declare @vCols varchar(max)

Create Table vTable1 (id int, StudentID int, Dept varchar(10),BookID int)
Create Table vTable2 (id int, StudentID int, Dept varchar(10),BookID int)

Insert into vTable1
Select 1,123,'CS',465 Union All
Select 2,123,'CS',345 Union All
Select 3,223,'TE',190

Insert into vTable2
Select 1,123,'CS',465 Union All
Select 2,223,'TE',345 Union All
Select 3,223,'TE',190

-- Get the column names from schema with case statements to get 0 or 1 as result
-- Now, this will depend upon the columns of your actual tables
-- Data approach
Select @vCols = Stuff((Select ',case when a.' + [name] + ' = b.' + [name] + ' then Cast(b.' + [name]+' as varchar(10)) else cast(b.' + [name] + ' as varchar(max)) + ''(old)'' + '' '' + Cast(a.' + [name] + ' as varchar(10)) + ''(new)'' end as ' +
[name] from sys.columns
where Object_id = Object_id('vTable1') for XML Path('')),1,1,'')

-- Concatenate the @vCols with main sql
Set @vSQL = ' Select a.id,' + @vCols + ' From vTable1 a
Inner Join vTable2 b on b.ID = a.ID '

Print @vSQL
Exec (@vSQL)

--Flag approach
Select @vCols = Stuff((Select ',case when a.' +
[name] + ' = b.'
+ [name] + ' then 1 else 0 end as ' +
[name] from sys.columns
where Object_id
= Object_id('vTable1') for XML Path('')),1,1,'')

Set @vSQL = ' Select a.id,' + @vCols + ' From vTable1 a
Inner Join vTable2 b on b.ID = a.ID '

Print @vSQL
Exec (@vSQL)


Drop table vTable1
Drop table vTable2

 

---the scripts written by Atif-ullah Sheikh

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值