create table t1(UID int,TITLE varchar(10),FIRSTNAME varchar(10),LASTNAME varchar(10))
insert into t1
select 0,'MR','A0','A00' union all
select 1,'MR','A1','A11' union all
select 2,'MR','A2','A22' union all
select 3,'MR','A3','A33' union all
select 4,'MR','A4','A44' union all
select 5,'MR','A5','A55'
create table t2(GID int,UID1 int, UID2 int, UID3 int, UID4 int)
insert into t2
select 100,0,1,2,null union all
select 200,3,4,null,null union all
select 300,5,null,null,null
select GID,
case when T.UID1 is not null then (select FIRSTNAME + ' ' + LASTNAME from t1 where UID=T.UID1) else '' end
+ case when (T.UID1 is not null) and (T.UID2 is not null) then (select '/' + FIRSTNAME + ' ' + LASTNAME from t1 where UID=T.UID2)
when (T.UID2 is not null) then (select FIRSTNAME + ' ' + LASTNAME from t1 where UID=T.UID2)
else '' end
+ case when (T.UID2 is not null) and (T.UID3 is not null) then (select '/' + FIRSTNAME + ' ' + LASTNAME from t1 where UID=T.UID3)
when (T.UID3 is not null) then (select FIRSTNAME + ' ' + LASTNAME from t1 where UID=T.UID3)
else '' end
+ case when (T.UID3 is not null) and (T.UID4 is not null) then (select '/' + FIRSTNAME + ' ' + LASTNAME from t1 where UID=T.UID4)
when (T.UID4 is not null) then (select FIRSTNAME + ' ' + LASTNAME from t1 where UID=T.UID4)
else '' end
from t2 T
create table t1(UID int,TITLE varchar(10),FIRSTNAME varchar(10),LASTNAME varchar(10))
insert into t1
select 0,'MR','A0','A00' union all
select 1,'MR','A1','A11' union all
select 2,'MR','A2','A22' union all
select 3,'MR','A3','A33' union all
select 4,'MR','A4','A44' union all
select 5,'MR','A5','A55'
create table t2(GID int,UID1 int, UID2 int, UID3 int, UID4 int)
insert into t2
select 100,0,1,2,null union all
select 200,3,4,null,null union all
select 300,5,null,null,null
go
create function fn_str(@gid int)
returns varchar(4000)
as
begin
declare @s varchar(4000)
set @s=''
select @s=@s+'/'+t1.firstname+' '+t1.lastname from t1,t2 where t2.gid=@gid and
(t1.uid=t2.uid1 or t1.uid=t2.uid2 or t1.uid=t2.uid3 or t1.uid=t2.uid4 )
return stuff(@s,1,1,'')
end
go
select gid ,names=dbo.fn_str(gid) from t2
--
drop table t1,t2
drop function fn_str
select t1.GID,isnull(t2.FIRSTNAME+' '+t2.LASTNAME,'')+
isnull('/'+t3.FIRSTNAME+' '+t3.LASTNAME,'')+
isnull('/'+t4.FIRSTNAME+' '+t4.LASTNAME,'')+
isnull('/'+t5.FIRSTNAME+' '+t5.LASTNAME,'')
from table2 t1 left join table1 t2 on t1.UID1 = t2.UID
left join table1 t3 on t1.UID1 = t3.UID
left join table1 t4 on t1.UID1 = t4.UID
left join table1 t5 on t1.UID1 = t5.UID
--try
create function dbo.fn_str(@gid int)
returns varchar(4000)
as
begin
declare @s varchar(4000)
set @s=''
select @s=@s+'/'+t2.firstname+' '+t2.lastname from t1,t2 where t2.gid=@gid and
(t1.uid=t2.uid1 or t1.uid=t2.uid2 or t1.uid=t2.uid3 or t1.uid=t2.uid4 )
return @s
end
go
select gid ,names=dbo.fn_str(gid) from tb