sql query for reading records one at a time

kandimal 1 Reputation point
2021-05-24T21:01:40.623+00:00

I need to read a Microsoft sql db table record one at a time (first in first out). we have Field1 with time stamp of insert of record into table. we have Field2 with value 'N". I need to pick the oldest record of table first with Value "N" on the basis of Field1 and Field2.

Can you advise the SQL query for this requirement ? I have a business requirement where in I need to read only one record at a time, and I am not explaining that business requirement here. I have batch job scheduled and will run every 5mins.

Thanks in Advance

kandimal

Developer technologies Transact-SQL
SQL Server Other
{count} votes

4 answers

Sort by: Most helpful
  1. Erland Sommarskog 121.4K Reputation points MVP Volunteer Moderator
    2021-05-24T21:44:52.48+00:00
    SELECT TOP(1) col1, col2, ...
    FROM   tbl
    WHERE Field2 = 'N'
    ORDER BY Field1
    

    There should be index like this:

    CREATE INDEX Field1_ix ON (Field1)  INCLUDE (Field2) WHERE Field2 = 'N'
    
    0 comments No comments

  2. MelissaMa-MSFT 24,221 Reputation points
    2021-05-25T02:06:08.737+00:00

    Hi @kandimal ,

    Welcome to Microsoft Q&A!

    You could also try with SET ROWCOUNT (N) which is similar with TOP (N).

    Please refer below:

    set rowcount 1  
      
    select *   
    from yourtable  
    where Field2='N'   
    order by Field1  
    

    Only one note is that once you have set rowcount this will persist for the life of the connection so make sure you reset it to 0 once you are done with it.

    Best regards,
    Melissa


    If the answer is helpful, please click "Accept Answer" and upvote it.
    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.


  3. Tom Phillips 17,771 Reputation points
    2021-05-25T13:54:53.99+00:00
    0 comments No comments

  4. Guoxiong 8,206 Reputation points
    2021-05-25T16:18:39.537+00:00

    If you do not want to delete the row which was read, you need a flag column to indicate it. See the example below:

    DECLARE @tbl TABLE (
        UniqueColumn int IDENTITY,
        Field1 datetime,
        Field2 char(1),
        IsRead bit default(0)
    );
    
    INSERT INTO @tbl(Field1, Field2) VALUES
    ('2021-05-01', 'N'), ('2021-05-02', 'Y'), ('2021-05-03', 'N'),
    ('2021-05-04', 'N'), ('2021-05-05', 'Y'), ('2021-05-06', 'N');
    
    DECLARE @UniqueColumn int;
    
    SELECT TOP 1 @UniqueColumn = UniqueColumn 
    FROM @tbl
    WHERE Field2 = 'N' AND IsRead = 0
    ORDER BY Field1
    
    UPDATE @tbl
    SET IsRead = 1
    WHERE UniqueColumn = @UniqueColumn;
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.