日期:2014-05-18 浏览次数:20683 次
go
create view test
as
select [nianfen]=dateadd(yy,t2.ID-1,t1.sj)
from
(select sj= '1998-05-06',sj2= '2002-01-04')t1
,
sysobjects t2
where
datediff(yy,t1.sj,t1.sj2)!<t2.ID-1
go
select * from test
nianfen
------------------------------------------------------
1998-05-06 00:00:00.000
1999-05-06 00:00:00.000
2000-05-06 00:00:00.000
2001-05-06 00:00:00.000
(所影响的行数为 4 行)
------解决方案--------------------
create view test
as
select [nianfen]=year(dateadd(yy,t2.ID-1,t1.sj))--改为显示年份
from
(select sj= '1998-05-06',sj2= '2002-01-04')t1
,
sysobjects t2
where
datediff(yy,t1.sj,t1.sj2)!<t2.ID-1
go
select * from test
nianfen
-----------
1998
1999
2000
2001
(所影响的行数为 4 行)
------解决方案--------------------
create proc test(
@sj datetime,--'1998-05-06'
@sj2 datetime--'2002-01-04'
)
as
declare @ta table(nianfen int)
while year(@sj)!>year(@sj2)
begin
insert @ta select year(@sj)
set @sj=dateadd(yy,1,@sj)
end
select * from @ta
go
exec test '1998-05-06','2002-01-04'
nianfen
-----------
1998
1999
2000
2001
2002
(所影响的行数为 5 行)
------解决方案--------------------
视图改一下:
create view test
as
select [nianfen]=dateadd(yy,t2.ID-1,t1.sj)
from
(select sj= '1998-05-06',sj2= '2002-01-04')t1
,
sysobjects t2
where
datediff(yy,t1.sj,t1.sj2)!<t2.ID-1
union all
select '2002-01-04' --添加记录
------解决方案--------------------
视图不可以传参:
漏了一个year:
create view test
as
select [nianfen]=dateadd(yy,t2.ID-1,t1.sj)
from
(select sj= '1998-05-06',sj2= '2002-01-04')t1
,
sysobjects t2
where
datediff(yy,t1.sj,t1.sj2)!<t2.ID-1
union all
select year('2002-01-04') --添加记录