首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 数据库 > SQL Server >

SQL 表比较,该如何处理

2013-04-02 
SQL 表比较两个表结构相同例如:T_a表ID Name Num DataT_b表ID Name Num Data比较这两个表,结果存入表T_Res

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

热点排行