使用while循环获取下一条记录

时间:2014-06-25 10:11:44

标签: sql sql-server

我不允许使用游标或临时表。我只能使用while循环。

表1 - 只读表(不可编辑)

id name

M01 Raja
M02 Ravi
M03 Vijay
M04 suresh

查询

Declare @TotRecord int, @CurrRecord Int, @id varchar(10)

Select @TotRec = COUNT(*) from Table1
Set @CurrRec = 1
WHILE (@CurrRec <=@TotRec)
BEGIN

--*Here i want to get the id from table, 
--next time i need to get second id. 
--next time i need to get third id.
--....

--1st time i can get the top 1 id by using this below query 
Select top 1 @id  = id from table 
--Next time i want to get second id.*


SET @CurrRec = @CurrRec + 1
END

6 个答案:

答案 0 :(得分:0)

使用

的模式
SELECT TOP 1 * FROM table WHERE id > @iterator ORDER BY id ASC

循环

答案 1 :(得分:0)

如果ID是序列号(M01,M02,M03,...),则可以在while循环中使用以下内容

SELECT TOP 1 @id = id FROM table WHERE CAST(REPLACE(id,'M','') AS INT)  = @CurrRecord

完整查询

DECLARE @TotRecord INT, @CurrRecord INT, @id VARCHAR(10)

SELECT @TotRecord = COUNT(*) FROM Table1
SET @CurrRecord = 1
WHILE @CurrRecord <= @TotRecord
BEGIN
    -- Get ID
    SELECT TOP 1 @id = id FROM Table1 WHERE CAST(REPLACE(id,'M','') AS INT) = @CurrRecord

    -- Do something

    SET @CurrRecord = @CurrRecord + 1
END

答案 2 :(得分:0)

您可以使用游标一对一地获取查询记录。

例如:

Declare @Col1 INT,
        @Col2 INT,
        ...


DECLARE X CURSOR FOR 
SELECT Col1, col2 , ...
FROM YourTableName


OPEN X
FETCH NEXT FROM X INTO @Col1, @Col2, ...
WHILE @@FETCH_STATUS=0 BEGIN
    --your code to do with columns data of your record
    FETCH NEXT FROM X INTO @Col1, @Col2, ...
END
CLOSE X
DEALLOCATE X

你也可以在哪里使用你的想法:

DECLARE @Id INT,
        @OldId INT,
        @Col1 INT,
        @Col2 INT
        ...

WHILE 1=1 BEGIN

    SET @OldId = @Id
    SET @Id = NULL

    SELECT TOP 1 @Id = Id, 
                 @Col1 = Column1,
                 @Col2 = Column2
    FROM YourTable 
    WHERE (@OldId IS NULL OR Id > @OldId) ORDER BY Id

    IF @Id IS NULL BREAK

    -- your Code Here
END

答案 3 :(得分:0)

DECLARE @TotRecord INT;
DECLARE @CurrRecord INT;
DECLARE @id VARCHAR(10);

SELECT @TotRecord = COUNT(*) from Table1;
SELECT @CurrRecord = 1;
SELECT TOP 1 @id  = id FROM Table1 ORDER BY id; 
WHILE (@CurrRecord <= @TotRecord)
BEGIN
    --Do something...
    --Get the next id
    SELECT TOP 1 @id = id FROM Table1 WHERE id > @id ORDER BY id;
    SELECT @CurrRecord = @CurrRecord + 1;
END;

但请注意,只有在表1中id是唯一的时才能使用。

答案 4 :(得分:0)

    Declare @TotRecord int, @CurrRecord Int, @id varchar(10)

    Select @TotRec = COUNT(*) from Table1
    Set @CurrRec = 1
    WHILE (@CurrRec <=@TotRec)
    BEGIN

    select LAST(id) from (SELECT TOP  @CurrRec id
    FROM Table1);

    //Here you will get the last record, i havent tried this, but iam sure about the logic , hope this one helps

    SET @CurrRec = @CurrRec + 1
    END

答案 5 :(得分:-1)

Select id,name,row_number() over (order by id) 'Row' into #temp
from table 

Select @id =  id from #temp where row = @current 

使用临时表获取下一个ID