sql server查询2010年到当前年的年份列表
1.函数
CREATE FUNCTION GetYears(@beginYear int)
returns @temptale table (text char(4) ,value int)
BEGIN
declare @now datetime = DATEADD(YEAR,1,getdate())
declare @nowChar char(4) = CONVERT(char(4),@now,120)
declare @nowInt int = CONVERT(char(4),@now,120)
while(@nowInt>=@beginYear)
begin
insert into @temptale select @nowChar,@nowInt
set @now = dateadd(year,-1,@now)
set @nowChar = CONVERT(char(4),@now,120)
set @nowInt = CONVERT(char(4),@now,120)
end
return
END
select * from GetYears(2010)
2.临时表
IF OBJECT_ID(N'tempdb.dbo.#PatientList') IS NOT NULL
DROP TABLE #PatientList;
DECLARE @year INT
SET @year = 2010;
CREATE TABLE tempdb.dbo.#PatientList
(
year INT
)
WHILE @year <= YEAR(GETDATE())+1
BEGIN
INSERT INTO #PatientList
(
year
)
VALUES
(@year -- year - int
)
SET @year = @year+1;
END
SELECT * FROM #PatientList;
DROP TABLE #PatientList;