27,579
社区成员
发帖
与我相关
我的任务
分享
select t1.* from A t1 ,B t2
where charindex(','+t1.ID+',',','+t2.ID_A+',')>0 and t2.name='张三'
declare @a table (id varchar(10),name varchar(10))
insert into @a select '101','语文'
insert into @a select '103','数学'
insert into @a select '201','英语'
declare @b table (name varchar(10),id_a varchar(50))
insert into @b select '张三','101,103'
insert into @b select '李四','103,201'
select * from @a a,@b b
where charindex(a.id,b.id_a)>0
and b.name='张三'
select t1.* from A t1 ,B t2
where charindex(','+ID+',',','t2.ID_A+',')>0 and t2.name=张三
select A.* from A,B where charindex(a.id,b.ID_A)>0
tba
ID classid name
1 1,2,3 西服
2 2,3 中山装
3 1,3 名裤
tbb
id classname
1 衣服
2 上衣
3 裤子
我得的结果是
id classname name
1 衣服,上衣,裤子 西服
2 上衣,裤子 中山装
3 衣服,裤子 名裤
create table tba(ID int,classid varchar(20),name varchar(10))
insert into tba values(1,'1,2,3','西服')
insert into tba values(2,'2,3' ,'中山装')
insert into tba values(3,'1,3' ,'名裤')
create table tbb(ID varchar(10), classname varchar(10))
insert into tbb values('1','衣服')
insert into tbb values('2','上衣')
insert into tbb values('3','裤子')
go
--第1种方法,创建函数来显示
create function f_hb(@id varchar(10))
returns varchar(1000)
as
begin
declare @str varchar(1000)
set @str=''
select @str=@str+','+[classname] from tbb where charindex(','+cast(id as varchar)+',',','+@id+',')>0
return stuff(@str,1,1,'')
end
go
select id,classid=dbo.f_hb(classid),name from tba
drop function f_hb
/*
id classid name
----------- ------------- ----------
1 衣服,上衣,裤子 西服
2 上衣,裤子 中山装
3 衣服,裤子 名裤
(所影响的行数为 3 行)
*/
--第2种方法.update
while(exists (select * from tba,tbb where charindex(tbb.id,tba.classid) >0))
update tba
set classid= replace(classid,tbb.id,tbb.classname)
from tbb
where charindex(tbb.id,tba.classid)>0
select * from tba
/*
ID classid name
----------- -------------------- ----------
1 衣服,上衣,裤子 西服
2 上衣,裤子 中山装
3 衣服,裤子 名裤
(所影响的行数为 3 行)
*/
drop table tba,tbb