怎樣在表中插入日期間斷的數據?在線等待,請高手指點.

現有一個表:

工號 日期
001 2003-01
001 2003-03
001 2003-05
002 2003-01
002 2003-04
. .
. .
. .

例如我想在表中插入 (001 2003-02) ,(001 2003-04),(002 2003-02),(002 2003-03) ,我試了一些方法好象不行.

---------------------------------------------------------------

insert into 表
select '001','2003-02'
union all select '001','2003-04'
union all select '002','2003-02'
union all select '002','2003-03'
---------------------------------------------------------------

select 1 -- 此句为了使@@rowcount > 0
while @@rowcount > 0
begin
insert 表 select 工号,convert(char(7),dateadd(month,1日期),121)
where not exists(Select 1 from 表 a where 工号 = a.工号 and datediff(month,日期,a.日期) = 1 and a.日期 <> (Select max(日期) from 表 b where 工号 = b.工号) )
end

---------------------------------------------------------------

create table 你的表(工號 varchar(10),日期 varchar(100))
insert into 你的表
select '001','2003-01'
union all select '001','2003-03'
union all select '001','2003-05'
union all select '002','2003-01'
union all select '002','2003-04'

insert 你的表 select 工號,CONVERT(char(7),dateadd(month,bb.rowid,aa.a),120) from (select 工號,min(日期)+'-01' a,max(日期)+'-01' b from 你的表 group by 工號)aa,(select top 300 (select count(*) from sysobjects where id<a.id) rowid from sysobjects a) bb where dateadd(month,bb.rowid,aa.a)<=aa.b and not exists(select 1 from 你的表 where 工號=aa.工號 and CONVERT(char(7),dateadd(month,bb.rowid,aa.a),120)=日期)

select * from 你的表 order by 工號,日期
go
drop table 你的表

Published At
Categories with 数据库类
Tagged with
comments powered by Disqus