Looping in select query

  • I am selecting 25 entries from the table

    For first five rows I want to add some common feature and select

    For next five rows I want to add some another feature and select

    till the end of the records.

    How to do this?

  • Hello,

    I am not really sure what you want to accomplish, may be you could provide an example? If you want to perform different actions for records within the same result set, then a “Case” statement could be what you need.

    Regards,

    John Marsh

    www.sql.lu
    SQL Server Luxembourg User Group

  • How about setting up some sample data for folks to test against?

    Cheers

    ChrisM

    “Write the query the simplest way. If through testing it becomes clear that the performance is inadequate, consider alternative query forms.” - Gail Shaw

    For fast, accurate and documented assistance in answering your questions, please read this article.
    Understanding and using APPLY, (I) and (II) Paul White
    Hidden RBAR: Triangular Joins / The "Numbers" or "Tally" Table: What it is and how it replaces a loop Jeff Moden

  • Hello,

    Either post sample data (CREATE TABLE, INSERT INTO statements) and required result plus some more info about the "features", or look up ranking functions (e.g. ROW_NUMBER()) and CASE statement in BooksOnLine.

  • sar_kan25 (2/2/2009)


    I am selecting 25 entries from the table

    For first five rows I want to add some common feature and select

    For next five rows I want to add some another feature and select

    till the end of the records.

    How to do this?

    May be this can help you:

    IF OBJECT_ID('Tally') IS NOT NULL

    DROP TABLE dbo.Tally

    GO

    SELECT TOP 100 IDENTITY(INT,1,1) AS ID

    INTO dbo.Tally FROM master.sys.all_objects (NOLOCK)

    GO

    DECLARE @RecordCounts as int,@Tile as int

    SELECT @RecordCounts = COUNT(*) FROM dbo.Tally

    SELECT @Tile = 5

    Select ID, NTILE(@RecordCounts/@Tile)OVER (Order By ID ) Feature

    From dbo.Tally

  • certainly by looking at your requirement it is not clear what you want and why? but anyway i think your problem can be either resolved with some smart logic using case statement or with using Cursors.

  • I think there is a keyword called ROWCOUNT which can be set like

    SET ROWCOUNT 5

    which means you will get output after first 5 rows... You can use this keyword and keep incrementing in order to acheive your results...

    Regards,
    Sakthi
    My Blog -> http://www.sqlserverdba.co.cc

Viewing 7 posts - 1 through 6 (of 6 total)

You must be logged in to reply to this topic. Login to reply