我需要创建一个存储过程,可以检查给定的开始年份和结束年份之间是否存在年份,并返回存在的年份。例如,如果我提供2000作为开始年份和2005年结束年份,那么它应该返回表格中存在的那些年份。我尝试了以下代码,但它无法正常工作。
ALTER PROCEDURE [dbo].[CheckExistenceforyear]
@StYear int = 0,
@EdYear int = 0,
@SubStationID int = 0,
@YrString varchar(255) = null Output
AS
BEGIN
SET NOCOUNT ON;
Declare @TempValue varchar(4)
if @StYear <= @EdYear
while @StYear <= @EdYear
Begin
if (select Count(Sub.Year) from table sub where Sub.Year=@StYear and Sub.SubStationID = @SubStationID) > 0
Begin
select @TempValue=Sub.Year from table as sub where Sub.Year=@StYear and Sub.SubStationID = @SubStationID
set @YrString = @YrString + @TempValue
End
set @StYear = @StYear +1
End
Else
return -1
select @YrString
END
答案 0 :(得分:2)
您可以使用简单查询,例如
SELECT DISTINCT YEAR FROM TABLE WHERE YEAR BETWEEN STARTYEAR AND ENDYEAR.
在WHERE子句中使用BETWEEN运算符来选择两个值之间的数据范围。