读书人

求教SQL,该如何处理

发布时间: 2012-03-14 12:01:12 作者: rapoo

求教SQL
有表1
a b
01 a1
02 a2

表2

c d
01 d1
02 d2
01 d3
02 d4
03 d5


要得到结果:
01,a1,d1、d3

如何写啊?


另:

qq群:19877329

[解决办法]
declare @a varchar(200)
select a,@a=coalesce(@a+ ', ', ' ')+b from (select a,b from tb1 Union All select c,d from tb2) aa where a= '01 '
[解决办法]
先union all 表


declare @str varchar(2000)
set @str= 'c, '
select @str=@str+d from (a 表union all b表) 表
print @str
[解决办法]
create function udf_getid(@p varchar(10))
returns varchar(8000)
as
begin
declare @p1 varchar(8000)

select @p1=isnull(@p1, ' ')+ d + ', ' from t2 where c=@p
select @p1=substring(@p1,1,len(@p1)-1)

return @p1
end

create table t1(a varchar(10) null,b varchar(10) null)
create table t2(c varchar(10) null,d varchar(10) null)

insert into t1(a,b) values( '01 ', 'a1 ')

insert into t1(a,b) values( '02 ', 'a2 ')

insert into t2(c,d)
select
'01 ', 'd1 ' union all select
'02 ', 'd2 ' union all select
'01 ', 'd3 ' union all select
'02 ', 'd4 ' union all select
'03 ', 'd5 '

select t1.a,dbo.udf_getid(t1.a) from t1

读书人网 >SQL Server

热点推荐