select RNo,t1.cname as CName_one,t2.cname as CName_two,t2.cname as CName_three,...
from table1 a
table2 t1,
table2 t2,
table2 t3,
...
where a.Cid_One=t1.Cid
and a.Cid_Two=t2.Cid
and a.CId_Three=t3.Cid
...
说清楚问题,好办事,是不是想要这个?
SELECT a.rno AS rno, b.cname AS cname_one, c.cname AS cname_two,d.cname as cname_three
FROM tab1 a INNER JOIN
tab2 b ON a.cid_one = b.cid INNER JOIN
tab2 c ON a.cid_two = c.cid INNER JOIN
tab2 d ON a.cid_three = d.cid
两个办法:
1、
select RNo
,(select CName from table2 where table1.CID_one=table2.CID) as CName_one
,(select CName from table2 where table1.CID_two=table2.CID) as CName_two
,(select CName from table2 where table1.CID_three=table2.CID) as CName_three
from table1
2、
select t0.RNo,t1.cName as CName_one,t2.cName as CName_two,t3.cName as CName_three
from table1 t0
inner join
table2 t1 on t0.cID_one=t1.cid
inner join
table2 t2 on t0.cID_two=t2.cid
inner join
table2 t3 on t0.cID_three=t3.cid
select RNo,CName_one,CName_two,CName_three
from table1
left join table2
on table1.cID_one=table2.cID
left join table2
on table1.cID_two=table2.cID
left join table2
on talbe1.cID-three=table2.cID
You also can put the table1 in cursor and fetch cursor for table2
以id为1的那行为例,就是要达到如下的效果:
Table1:
id variable
name1 aa
name2 bb
name3 cc
……………….
我的解决方案:
declare @vVariable varchar(2000),@var varchar(2000) --中間值的變量
declare @sql nvarchar(4000) -- 動態sql
declare @insertSql varchar(4000) -- 插入臨時表的sql
set @vVariable = ' '
if object_id('tempdb.dbo.#temp1') is not null
drop table #temp1
select identity(int) id,name into #temp1 from syscolumns where id = object_id('Table2') and name <> 'id' order by colid
if object_id('tempdb.dbo.#temp2') is null -- 創建臨時表#temp2
create table #temp2
(
id int identity,
variable varchar(10)
)
else
truncate table #temp2
select @vVariable = @vVariable + '+'',''+' + name from syscolumns where id =
object_id('Table2') and name <> 'id' order by colid
set @vVariable = right(@vVariable,len(@vVariable) - 6)
set @sql = 'select @var = '+@vVariable+' from Table2 where id = 1'
exec sp_executesql @sql,N'@var varchar(2000) output',@var output -- 組成以逗號分格的變量@var
set @insertSql='insert into #temp2 values('''+REPLACE(@var,',',''')
insert into #temp2 values(''')+''')'
exec (@insertSql) -- 根據變量中的逗號分格插入臨時表
insert into Table1(id,variable)
select name,variable from #temp1,#temp2
where #temp1.id = #temp2.id