SQL查询循环给定数据

时间:2014-02-12 09:24:38

标签: sql sql-server sql-server-2008

我有以下表格的数据

  ID              Description
-------     ------------------------
83633       Reserves - 1  
83634       Reserves - 2
83635       Reserves - Total
83636       X Reserves  
83637       E Reserves  
83638       Oil 
83639       NGL 
83640       NB Gas  
83641       NU Gas
102195      Proved Reserves - D
102196      Proved Reserves - U
102197      Proved Reserves - Total 
102198      Probable Reserves - Gross
102199      Proved Reserves - G1
102200      Proved Reserves - G2
102201      Proved Reserves - G3
102202      Proved Reserves - G4
102203      Proved Reserves - N1
102204      Proved Reserves - N2
102205      Proved Reserves - N3
102206      Proved Reserves - N4
102207      Probable Reserves - G1
102208      Probable Reserves - G2
102209      Probable Reserves - G3
102210      Probable Reserves - G4
102211      Oil 
102212      NGL 
102213      CNG
102214      Natural Gas

我希望编写一个查询来选择仅增加1的Id。例如,如果我给出起始ID=83633,则查询应该返回以下数据

  ID              Description
-------     ------------------------
83633       Reserves - 1  
83634       Reserves - 2
83635       Reserves - Total
83636       X Reserves
83637       E Reserves  
83638       Oil 
83639       NGL 
83640       NB Gas  
83641       NU Gas

遇到ID = 102195时,查询必须停止执行。在此先感谢您的帮助!!

2 个答案:

答案 0 :(得分:2)

请尝试:

SELECT
    ID,
    Description
FROM(
    SELECT 
        ID+1-ROW_NUMBER() OVER (ORDER BY ID) Col,
        * 
    FROM YourTable
    WHERE ID>=83633
)x WHERE Col=83633

答案 1 :(得分:0)

您可以按如下方式使用'While'循环:

DECLARE @Temp INT

SELECT @Temp =83633
WHILE(@Temp <=102195)
BEGIN
        PRINT CHAR(@Temp )
        SELECT @Temp = @Temp + 1
END
GO