我需要在所有ID中添加缺席日期(不包括周末)。我必须循环使用超过100种不同的身份证。 到目前为止,我有以下代码:
declare @date_idx datetime
declare @date_missing datetime
declare @tsID int
declare @MyCursor CURSOR
--declare @tsIDnew int
set @date_idx = '20090101'
set @MyCursor = CURSOR fast_forward
FOR
select
tsID
--,@tsIDnew
from #tempTimeSeriesDateAdded
open @MyCursor
fetch next from @MyCursor
into @tsId
while @@FETCH_STATUS = 0
begin
while datediff(dd, @date_idx, '20150529') >= 0
BEGIN
set @date_missing = (select rateDate from #tempTimeSeriesDateAdded where rateDate = @date_idx and tsID = @tsID )
if DATEPART(DW, @date_idx) NOT IN (1,7) and @date_missing is null
--insert @date_idx into
PRINT @date_idx
SET @date_idx = DATEADD(dd,1,@date_idx)
END
fetch next from @MyCursor
--into @tsIDnew
end
close @MyCursor
Deallocate @MyCursor
如何让它发挥作用? 我对sql很新,并且昨天开始使用游标(我知道一组或一个联接可能会更好,我可以使用解决方案)。
谢谢
修改 我有这样的事情:
Ratedate rate
20.12.2012 0.152
21.12.2012 0.181
22 weekend so it's skipped (they are skipped automatically)
23 weekend -,-
24 missing
25 missing
26 missing
27.12.2012 0.173
28.12.2012 0.342
我想要这样的事情:
rateDate rate
20.12.2012 0.152
21.12.2012 0.181
22 weekend so it's skipped (they are skipped automatically)
23 weekend 0.181
24 missing 0.181
25 missing 0.181
26 missing 0.181
27.12.2012 0.173
28.12.2012 0.342
但我需要为列表中的每个tsId执行此操作。
编辑2:与我之前的帖子不重复。由于这是进一步的,编写代码并需要一个循环
答案 0 :(得分:1)
您应该删除光标和while循环。 此脚本为您提供开始日期和结束日期之间的所有缺失日期以及ID:
--create table #tempTimeSeriesDateAdded (tsid int)
declare @tempTimeSeriesDateAdded table (tsID int, dt datetime)
insert into @tempTimeSeriesDateAdded values
(1, '20150810'), (1, '20150818'), (1, '20150819'), (1, '20150820'), (1, '20150825')
, (2, '20150810'), (2, '20150812'), (2, '20150817'), (2, '20150820'), (2, '20150825')
declare @date_start datetime = '20150809'
declare @date_end datetime = '20150829'
-- all date between start and end
; with list as (
Select dt = @date_start
Union All
Select DATEADD(day, 1, dt) From list
Where DATEADD(day, 1, dt) <= @date_end
)
--Insert Into YourTable(date, id)
Select i.dt, i.tsID From (
Select tsID, dt
From (select distinct tsID from @tempTimeSeriesDateAdded) as idx
Cross Join list as l
where DATEPART(dw, dt) between 2 and 6
) as i
Left Join @tempTimeSeriesDateAdded as d on d.dt = i.dt and d.tsID = i.tsID
Where d.tsID is null
Order By i.tsID, i.dt
OPTION (MAXRECURSION 0);
您只需添加费率并插入即可。