SQL Server表中的多个查找

时间:2016-06-24 15:18:48

标签: sql-server

下面是我的两个表架构:

表1:

 id        int
 result   varchar

表2:

 id           int
 description  varchar

表1包含:

1 ; 1,4
2 ; 2
3 ; 2,3

表2包含:

1 : Bike
2 : Car
3 : Train
4 : Airplane

我现在想做一个显示

的查询
1  Bike, Airplane
2  Car
3  Car, Train

我如何获得描述?

Select t1.id, t2.description 
from t1, t2 
where..... ?

如果t1.result有一个值就很容易了。但是如果有更多的值用逗号分隔,我该怎么办?

谁可以提供帮助?

1 个答案:

答案 0 :(得分:0)

以下是您希望结果的完整sql脚本... 我在这里考虑

CREATE TABLE [dbo].[t1](
    [id] [int] NULL,
    [Result] [varchar](50) NULL
)

如表1所示 和

CREATE TABLE [dbo].[t2](
    [id] [int] NULL,
    [description] [nvarchar](50) NULL
)

作为table2 和bellow是你完整的sql server脚本.....

declare @Table table(Recid int identity, id int,Descp varchar(50))
create table #temp( id int,Descp varchar(50))
 insert into @Table
 select * from t1
declare @i int,@cnt int,@Str varchar(50),@Ids int,@StrQuery varchar(max)
select @cnt=count(*),@i=1 from @Table
 while @i<=@cnt
 begin
  select @str='(' + Descp +')',@Ids=id from @Table where Recid=@i
  set @StrQuery=' insert into #temp select ' +cast( @Ids as varchar(10)) + ', description from t2 where cast(id as varchar(10)) in ' + @str
  exec (@StrQuery)
  set @i=@i+1
 end
 declare @Table1 table(Recid int identity, id int,Descp varchar(50))
 insert into @Table1(id)
  select distinct id from #temp
  declare @Id int

  select @cnt=count(*),@i=1 from @Table1
while @i<=@cnt
begin
    select @Id=id from @Table1 where RecID =@i
    set @str =''
    SELECT  @str = COALESCE(@str + ',', '') + Descp 
    FROM #temp where id=@id
    update @Table1 set Descp =@str where id=@id
    set @i=@i+1
 end
  select id,RIGHT(RTRIM(Descp), LEN(Descp) - 1) from @Table1