Select Top Nth Record

  • Not very performant I think. To speed it up a bit, you can put all the code into a stored procedure.

    Another thing you can try is this:

    CREATE TABLE #Top

    (Pos INT IDENTITY (1,1) NOT NULL,

    chCustomer VARCHAR(50), -- this should be the same data types you use

    chLocation VARCHAR(50)) -- this should be the same data types you use

    INSERT INTO #Top

    (chCustomer, chLocation)

    SELECT chCustomer, chLocation

    FROM  TB_CustomerMaster

    SELECT chCustomer, chLocation

    FROM #Top

    WHERE Pos = 19

    DROP TABLE #Top

  • I have also done it before using temp tables with a identity field.  The purpose of the post above was someone needed it in a straight select statement.

    Thanks for the reply!

  • Depending on the data size it can get intensive. But to add to the temp table idea you can also do this to conserve a bit.

    INSERT INTO #Top

    (chCustomer, chLocation)

    SELECT TOP 19 chCustomer, chLocation

    FROM  TB_CustomerMaster

    SELECT chCustomer, chLocation

    FROM #Top

    WHERE Pos = 19

     

    But the above requires dynamic SQL to meet many needs might also try this

    SET @@rowcount @pos

    INSERT INTO #Top

    (chCustomer, chLocation)

    SELECT chCustomer, chLocation

    FROM  TB_CustomerMaster

    SET @@rowcount 0

    SELECT chCustomer, chLocation

    FROM #Top

    WHERE Pos = @pos

Viewing 3 posts - 1 through 4 (of 4 total)

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