循环表的每个记录并将数据插入临时表中,连接SQL中的另一个临时表

时间:2013-04-30 06:18:19

标签: sql sql-server-2008 sql-server-2005

我有两个临时表#CoreUtilizationForRole1#RoleID2Details。我想使用这两个临时表将值插入第三个临时表。 下面是Temp表的结构表。

create table #CoreUtilizationForRole1(roleid int,SupervisorName varchar(50),ImmediateSupervisor varchar(50),UserECode varchar(50),UserName nvarchar(250),Designation varchar(250),TimeSpent float,ActivityName varchar(250))

create table #RoleID2Details(UserECode varchar(50),UserName nvarchar(250))

#CoreUtilizationForRole1表中我生成了一个报告并存储在其中。 #RoleID2Details包含查询中提到的数据: -

insert into #RoleID2Details
    select distinct Userecode,Username from #CoreUtilizationForRole1 where roleid=2

现在我想循环遍历#RoleID2Detail的每个记录,并在从#CoreUtilizationForRole1加入时将数据插入第三个临时表。 实际上我需要特定描述格式的数据,因此需要这种循环,以便根据我的要求将数据插入第三个临时表,然后使用简单的select语句,我将显示它。

第三个表格结构将是 -

create table #ThirdtempTable(roleid int,SupervisorName varchar(50),ImmediateSupervisor varchar(50),UserECode varchar(50),UserName nvarchar(250),Designation varchar(250),TimeSpent float,ActivityName varchar(250))

并且将数据插入#ThirdtempTable的逻辑就像这样循环#RoleID2Details表的每个记录 -

insert into #ThirdtempTable
Select A.RoleId,A.SuperVisorName,A.Userecode,A.Username,A.Designation,A.TimeSpent,A.ActivityName 
from #CoreUtilizationForRole1 A 
inner join #RoleID2Details B 
on
A.SuperVisorName=B.UserName
where B.UserECode= --First UserECode from #RoleID2Details

insert into #ThirdtempTable
Select A.RoleId,A.SuperVisorName,A.Userecode,A.Username,A.Designation,A.TimeSpent,A.ActivityName 
from #CoreUtilizationForRole1 A 
inner join #RoleID2Details B 
on
A.UserName=B.UserName
where A.UserECode=--First UserECode from #RoleID2Details

这个循环将一直持续到我们从#RoleID2Details表中提取所有记录并将其如上所述插入到#ThirdtempTable表中。

1 个答案:

答案 0 :(得分:2)

insert into #your3rdTempTable
select distinct t1.UserECode,t1.UserName from
#CoreUtilizationForRole1 t1 join #RoleID2Details t
on t1.UserECode=t2.UserECode and t1.UserName = t2.UserName 

您可以尝试这种方式:

insert into #ThirdtempTable
Select A.RoleId,A.SuperVisorName,A.Userecode,A.Username,A.Designation,A.TimeSpent,A.ActivityName 
from #CoreUtilizationForRole1 A 
inner join #RoleID2Details B 
on
A.SuperVisorName=B.UserName
where B.UserECode=A.UserECode

insert into #ThirdtempTable
Select A.RoleId,A.SuperVisorName,A.Userecode,A.Username,A.Designation,A.TimeSpent,A.ActivityName 
from #CoreUtilizationForRole1 A 
inner join #RoleID2Details B 
on
A.UserName=B.UserName
where A.UserECode=A.UserECode