这个两表连接更新的语句该怎样写啊?
A表: c1 c2
a YES
b YES
c YES
d NO
B表: id c1
1 a
2 a,b,c
3 a,c
现在我根据B表c1的值,到A表c1中去查找,如果存在,就令A.c2=YES,否则为NO
例如:B.c1=a,b,c,就把A.c1为a,b,c的记录的c2改为YES
如果B.c1是个单值的字段,很好写,但是,它现在可能是单值,也可能是多值的,例如:a,b,c
这个update语句该如何写呢?要求有一个语句来实现。
[解决办法]
declare @A表 table (c1 varchar(1),c2 varchar(8))insert into @A表select 'a',null union allselect 'b',null union allselect 'c',null union allselect 'd',nulldeclare @B表 table (id int,c1 varchar(10))insert into @B表select 1,'a' union allselect 2,'a,b,c' union allselect 3,'a,c'update @A表set c2=case when b.id is null then 'No' else 'Yes' endfrom @A表 a left join @B表 b on charindex(','+a.c1+',',','+b.c1+',')>0select * from @A表/*c1 c2---- --------a Yesb Yesc Yesd No*/
[解决办法]
USE CSDNGOdeclare @A表 table (c1 varchar(1),c2 varchar(8))insert into @A表select 'a',null union allselect 'b',null union allselect 'c',null union allselect 'd',nulldeclare @B表 table (id int,c1 varchar(10))insert into @B表select 1,'a' union allselect 2,'a,b,c' union allselect 3,'a,c'UPDATE ASET c2 = (CASE WHEN EXISTS(SELECT 1 FROM @B表 B WHERE CHARINDEX(','+A.c1+',', ','+B.c1+',') > 0) THEN 'YES' ELSE 'NO' END)FROM @A表 AWHERE c2 IS NULL/*c1 c2a YESb YESc YESd NO*/