2013-01-05 95 views
0

我需要創建一個存儲過程,它可以檢查給定的開始和結束年份之間是否存在年份並返回存在的年份。例如,如果我提供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 [email protected] and Sub.SubStationID = @SubStationID) > 0 
      Begin 

      select @TempValue=Sub.Year from table as sub where [email protected] and Sub.SubStationID = @SubStationID 
       set @YrString = @YrString + @TempValue 
      End 
      set @StYear = @StYear +1 
     End 
    Else 
     return -1 

    select @YrString  
END 

回答

2

可以使用簡單的查詢等

SELECT DISTINCT YEAR FROM TABLE WHERE YEAR BETWEEN STARTYEAR AND ENDYEAR. 

BETWEEN操作者以用於WHERE子句兩個值之間選擇一個範圍的數據。