数据的不规则填充
表A
ID 电话号码
1 95347287
1 29475827
2 56320928
3 13454656
3 45095698
3 22224522
3 22472222
4 67320987
……
表B
ID 电话号码
1 12345678
1
1
2 24566446
2
3 98567634
3
3 24654756
3
3
3
4 64567745
4
……
用表A中ID与表B中ID相同的数据,填充表B“电话号码”字段的空值,使填充后表B的数据如下:
ID 电话号码
1 12345678
1 95347287
1 29475827
2 24566446
2 56320928
3 98567634
3 13454656
3 24654756
3 45095698
3 22224522
3 22472222
4 64567745
4 67320987
……
[最优解释]
declare @表A table (ID int,电话号码 int)
insert into @表A
select 1,95347287 union all
select 1,29475827 union all
select 2,56320928 union all
select 3,13454656 union all
select 3,45095698 union all
select 3,22224522 union all
select 3,22472222 union all
select 4,67320987
declare @表B table (ID int,电话号码 int)
insert into @表B
select 1,12345678 union all
select 1,null union all
select 1,null union all
select 2,24566446 union all
select 2,null union all
select 3,98567634 union all
select 3,null union all
select 3,24654756 union all
select 3,null union all
select 3,null union all
select 3,null union all
select 4,64567745 union all
select 4,null
;with m1 as
(
select row_number() over
(partition by ID order by (select 1)) as rid,* from @表A
)
,m2 as
(
select row_number() over
(partition by ID order by (select 1)) as rid,* from @表B where 电话号码 is null
)
select b.ID,a.电话号码,1 as [sign] from m1 a
left join m2 b on a.ID=b.ID and a.rid=b.rid
union all
select *,0 from @表B where 电话号码 is not null
order by 1,3
--前面两列就是你想要的结果,如果有主键,按照唯一主键对应更新即可。
/*
ID 电话号码 sign
----------- ----------- -----------
1 12345678 0
1 95347287 1
1 29475827 1
2 24566446 0
2 56320928 1
3 98567634 0
3 24654756 0
3 13454656 1
3 45095698 1
3 22224522 1
3 22472222 1
4 64567745 0
4 67320987 1
*/
[其他解释]
1."你这个复制到另外一张表成功了吗?第一次就出现超过内存然后挂掉了?"——没有成功,Management Studio挂了,所以原来的表中那些数据是整不回来了。
2.假设原数据库为D1,其中误删数据的表为T1,新建了一个数据库为D2。
3.找到一个11月1日的备份,我将它恢复到了新建的数据库D2中(即目前有两个名称不同但结构相同的数据库,其中有表T2与D1.T1结构相同且历史数据基本都在)。
4.现在的目标是将D2.T2.TEL列的数据UPDATE到D1.T1的TEL列中,条件是:
D2.T2.ID = D1.T1.ID (ID字段就是主键)
Len(D2.T2.TEL) > 7
D1.T1.TEL = '' (且目标列必须为空,若已有数据,即使满足上面两个条件也不更新)
----------------------------------------------
PS:研究这个问题给我最大的感受是:问题能不能解决已经不是最重要的了,最重要的是:解决过程中得到了的经验和积累,哪怕只是一点一滴。感谢版主及本帖中各位热心人的赐教!