create table t1(year int,month int,[key] varchar(5))
go
insert t1
select 2013,12,'A' union all
select 2014,1,'A' union all
select 2014,2,'A' union all
select 2014,3,'A' union all
select 2013,12,'B' union all
select 2014,1,'B' union all
select 2014,2,'B' union all
select 2014,3,'B' union all
select 2014,4,'B' union all
select 2014,5,'B' union all
select 2014,6,'B' union all
select 2014,7,'B' union all
select 2014,8,'B'
go
create type tt as table
(
[key] varchar(5)
--这里其他字段就不创建了,实际业务中有很多其他信息
)
go
create proc proc_test
@year int,
@month int,
@data tt readonly
as
begin
--测试一传入的参数,key为‘B’的记录已经到2014-8不做处理。
--而‘A’的记录是2014-3,则需要补充5条记录,
--如:select 2014,4,'A' union all
--select 2014,5,'A' union all
--select 2014,6,'A' union all
--select 2014,7,'A' union all
--select 2014,8,'A' union all
select * from t1
end
go
--测试一
declare @data tt
insert @data
select 'A' union all
select 'B'
exec proc_test 2014,8,@data
注释中有说明
------解决思路----------------------
你建立一个表A年月表,里面只有一列(201401,201402.。。)里插入的时候用
select distinct [key]from t1 cross join a where a.years<把存储过程里面的参数转换下。and not exists ..
------解决思路----------------------
以为tt是你的表,原来是个类型。那直接用@data当左表就行
with n as (
select number
from master..spt_values v
where v.type='p'
)
insert into t1
select
(t2.year*12+t2.month+t3.number-1)/12
,(t2.year*12+t2.month+t3.number-1)%12 +1
,tt.[key]
from @data tt
cross apply(select top 1 * from t1 where t1.[key]=tt.[key] order by 1 desc,2 desc) t2
cross apply(select * from n where n.number between 1 and (@year*12+@month-(t2.year*12+t2.month))) t3