日期:2014-05-18  浏览次数:20530 次

急,求如下视图!
己知开始时间sj和结束时间sj2
求这两个时间之间年份的视图。
例如:sj='1998-05-06',sj2='2002-01-04'
需要得到如下视图:
nianfen
1998
1999
2000
2001
2002

------解决方案--------------------
用存储过程比较实际一点
------解决方案--------------------
如果用视图也等同于
一个一个select 

------解决方案--------------------
如果楼主要这样效果:
SQL code

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 行)

------解决方案--------------------
SQL code
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 行)

------解决方案--------------------
SQL code

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') --添加记录