循环遍历表以创建临时表

时间:2016-07-11 18:16:56

标签: sql-server tsql temp

我有一个表有一个日期字段,它是周数,然后是7个十进制字段,代表工作小时数。

我想循环遍历此表,并在每周的每一天在临时表中创建一行,每天工作的小时数。

我可以做一个简单的......

SELECT  UserID, WeekNum, Hours1, Hours2, Hours3, Hours4, Hours5, Hours6, Hours7
INTO    #NCExtract
FROM    Timesheet

但我需要一个结果

UserID Date Hours
UserID Date Hours
UserID Date Hours
UserID Date Hours
UserID Date Hours
UserID Date Hours
UserID Date Hours

从一行开始。所以我开始以下方式:

create table #NCExtract
(
    UserID int, 
    WorkDate DateTime, 
    WorkHours decimal
) 

Select *
From   TimeSheetTable

While (Select Count(*) From TimeSheetTable) > 0
Begin
    Create #NCExtract record with 1st date hours
    Create #NCExtract record with 2nd date hours
    Create #NCExtract record with 3rd date hours
    Create #NCExtract record with 4th date hours
    Create #NCExtract record with 5th date hours
    Create #NCExtract record with 6th date hours
    Create #NCExtract record with 7th date hours
End

我不知道如何在循环中提供信息来创建记录。

1 个答案:

答案 0 :(得分:0)

我可以想出两种方法来做你想做的事情(假设是t-sql,但也适用于其他数据库)。

unpivot:https://technet.microsoft.com/en-us/library/ms177410(v=sql.105).aspx

或7个选择语句(粗略近似见下文)

--Since i do not have a table definition of timesheet table might be a little off
create table #NCExtract ( UserID int, WorkDate DateTime, WorkHours decimal )

insert into #NCExtract (UserID, WorkDate, WorkHours)
Select Userid, DateAdd(d,1,WeekNum), Hours1 -- I assumed that the weeknum column was a date/datetime
From TimeSheetTable 
Where Hours1 is not null -- add any needed logic (e.g. not null or <> 0)

insert into #NCExtract (UserID, WorkDate, WorkHours)
Select Userid, DateAdd(d,2,WeekNum), Hours2 --update the date add for each select
From TimeSheetTable
Where Hours2 is not null

--3, 4, 5, 6 ommited

select * from #NCExtract 
order by UserID, WorkDate -- if the final result needs to be sorted, sort when selecting