当前位置: 代码迷 >> Sql Server >> SQL 表比较,该如何处理
  详细解决方案

SQL 表比较,该如何处理

热度:58   发布时间:2016-04-24 23:10:31.0
SQL 表比较
两个表结构相同
例如:
T_a表
ID Name Num Data

T_b表
ID Name Num Data

比较这两个表,结果存入表T_Result表
T_Result表
ID int,
NameState int,
NumState int,
DataState int

如果T_a表中的Name为NULL,T_b表中的Name不为NULL,则T_Result表中的NameState为0.
如果T_a表中的Name不为NULL,T_b表中的Name为NULL,则T_Result表中的NameState为1.
如果T_a表中的Name不为NULL,T_b表中的Name不为NULL,且他们的值不同,则T_Result表的NameState为1

同样的道理设置NumState和DataState的值。
sql

------解决方案--------------------
select isnull(a,id,b.id) as id
   ,case when a.name = b.name or a.name is null and b.name ia null then 1 else 0 end as NameState
   ,...
from t_a a full join t_b b
on a.id = b.id
------解决方案--------------------
insert into TResult
select a.id ,case when isnull(a.name,'' = '') and isnull(b.name,'' <> '') then 0
when  isnull(a.name,'' <> '') and isnull(b.name,'' = '') then 1
when  isnull(a.name,'' <> '') and isnull(b.name,'' <> '') and a.name <> b.name  then 1
end
from a ,b where a.id = b.id 

--NumState和DataState的值,参照name
  相关解决方案