2个表处理的问题
请帮忙看看:
一、有2个表,
表1:MainTable (现有记录数在10万条左右)
字段:
id bigint自动编号
Title nvarchar(30)
SubId nvarchar(max)
表MainTable:
Id Title SubId
1 A 0
2 B 0
3 C 0
4 D 0
5 E 0
6 F 0
表2:SubTable (现有记录数在300万条左右)
字段:
id bigint自动编号
Description nvarchar(100)
Fl int '默认值为0,当进行模糊匹配后,值改为1
表SubTable:
Id Description Fl
1 ABC 0
2 AB 0
3 CD 0
4 EA 0
二、需要实现的结果为:
表MainTable:
Id Title SubId
1 A 0,1,2,4
2 B 0,1,2
3 C 0,1,3
4 D 0,3
5 E 0,4
6 F Null
第6条记录由于没有匹配的值,所以改为Null
表SubTable:
Id Description Fl
1 ABC 1
2 AB 1
3 CD 1
4 EA 1
[解决办法]
create table MainTable(Id int, Title varchar(20),SubId nvarchar(max))
insert into MainTable
select 1 ,'A', 0 union all
select 2 ,'B', 0 union all
select 3 ,'C', 0 union all
select 4 ,'D', 0 union all
select 5 ,'E', 0 union all
select 6 ,'F', 0
create table SubTable(Id int,Description varchar(20),Fl int)
insert into SubTable
select 1 ,'ABC',0 union all
select 2 ,'AB',0 union all
select 3 ,'CD',0 union all
select 4 ,'EA',0
go
--1.修改数据
update MainTable
set SubId =cast(MainTable.SubId as varchar) +
(select ','+ CAST(t.ID as varchar)
from SubTable t
where t.Description like '%'+MainTable.Title+'%'
for xml path('')
)
--查询修改后的数据
select * from MainTable
/*
IdTitleSubId
1A0,1,2,4
2B0,1,2
3C0,1,3
4D0,3
5E0,4
6FNULL
*/
--2.修改 SubTable
update SubTable
set Fl = 1
from MainTable m
where SubTable.Description like '%'+m.Title+'%'
select * from SubTable
/*
IdDescriptionFl
1ABC1
2AB1
3CD1
4EA1
*/
create table MainTable
(id bigint,
Title nvarchar(30),
SubId nvarchar(max))
insert into MainTable
select 1,'A','0' union all
select 2,'B','0' union all
select 3,'C','0' union all
select 4,'D','0' union all
select 5,'E','0' union all
select 6,'F','0'
create table SubTable
(id bigint,
Description nvarchar(100),
Fl int)
insert into SubTable
select 1,'ABC',0 union all
select 2,'AB',0 union all
select 3,'CD',0 union all
select 4,'EA',0
-- 更新MainTable
update a
set a.SubId=
cast('0'+(select ','+rtrim(b.id)
from SubTable b
where charindex(a.Title,b.description,1)>0
order by b.id
for xml path('')) as nvarchar)
from MainTable a
select * from MainTable
/*
id Title SubId
-------------------- ------------------------------ -------------------
1 A 0,1,2,4
2 B 0,1,2
3 C 0,1,3
4 D 0,3
5 E 0,4
6 F NULL
(6 row(s) affected)
*/
-- 更新SubTable
update a
set a.Fl=case when exists(select 1 from MainTable b
where charindex(b.Title,a.description,1)>0)
then 1 else 0 end
from SubTable a
select * from SubTable
/*
id Description Fl
-------------------- ----------------- -----------
1 ABC 1
2 AB 1
3 CD 1
4 EA 1
(4 row(s) affected)
*/