两表对比,找出不同数据并更新
表A:
JD_DM, JF_DM, ZD_ZH, ZD_FH, OLD_ZDBH zd_id
00301121303011021-03 1
0030123603012003-06 2
0030189003018009 3
001 08983001089083 4
001 08921201089021-02 5
表B;
old new id
03011021-03 03011021-03 null
03012003-06 03012003-08 null
03018009 03018009 null
01089083 01089083-01 null
01089021-02 01089021-02 null
我现在想得到这样的结果:
1.A表的OLD_ZDBH和B表的old字段相同,同时A表的JD_DM+JF_DM+ZD_ZH+ZD_FH == B表的new字段
像:03011021-03 03表示 JD_DM, 011表示JF_DM, 012表示ZD_ZH,-03表示ZD_FH
(像zd_zh就要补位数,像21 应该补成021,长度应该为三位)(zd_fh如果为0就不用加上去,不为0时就像:3-->-03,长度也应该是三位),如果有相同的数据,就要把A表的zd_id字段值写到B表ID字段
2.A表的OLD_ZDBH和B表的old字段值相同,同时A表的JD_DM+JF_DM+ZD_ZH+ZD_FH <> B表的new字段
(同上)
请大家帮帮忙~~很急啊~~
[解决办法]
--第一个问题:create table A(JD_DM varchar(10),JF_DM varchar(10),ZD_ZH int,ZD_FH int,OLD_ZDBH varchar(20),zd_id int)insert into A values('003','011',21,3,'03011021-03',1) insert into A values('003','012',3 ,6,'03012003-06',2) insert into A values('003','018',9 ,0,'03018009' ,3) insert into A values('001','089',83,0,'01089083' ,4) insert into A values('001','089',21,2,'01089021-02',5) create table B(old varchar(20),new varchar(20),id int)insert into B values('03011021-03','03011021-03',null) insert into B values('03012003-06','03012003-08',null) insert into B values('03018009' ,'03018009' ,null) insert into B values('01089083' ,'01089083-01',null) insert into B values('01089021-02','01089021-02',null) goupdate Bset id = t.zd_idfrom B,( select right(JD_DM,2) JD_DM, JF_DM, right('000'+cast(ZD_ZH as varchar(3)),3) ZD_ZH, ZD_FH = case zd_fh when 0 then '' else right('00'+cast(zd_fh as varchar(2)),2) end, OLD_ZDBH,zd_id from A) twhere b.old = t.OLD_ZDBH and b.new = t.jd_dm + t.jf_dm + t.zd_zh + '-' + t.zd_fhselect * from bdrop table a,b/*old new id -------------------- -------------------- ----------- 03011021-03 03011021-03 103012003-06 03012003-08 NULL03018009 03018009 NULL01089083 01089083-01 NULL01089021-02 01089021-02 5(所影响的行数为 5 行)*/