Dynamic "TOP" values in select statements

  • I know there has to be a way to dynamically tell a select statement the top value without having to build the sql and then use the exec command. I tried this

    declare @top int

    set @top = 100

    select top @top policynumbers from tblpolicynumbers

    and that didn't work, obviously. Does anyone know how I can accomplish this?

    Thanks!

    Michael

  • Only way I have ever heard of is with dynamic sql.


  • You want to use SET ROWCOUNT @top before your query and SET ROWCOUNT 0 afterwards.

    DECLARE @top int

    SET @top = 100

    SET ROWCOUNT @top

    SELECT policynumbers FROM tblpolicynumbers

    SET ROWCOUNT 0

  • You should review BOL for SET ROWCOUNT as there are warnings about using this in updates,deletes, and inserts.

    If you are just doing selects then you should be ok.


  • This works in SQL 2005, but ot in SQL 2000. In 2000, the only ways to do this are dynamic SQL or RowCount

    Gail Shaw
    Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
    SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability

    We walk in the dark places no others will enter
    We stand on the bridge and no one may pass
  • two ways

    1

    DECLARE @top int

    SET @top = 100

    SET ROWCOUNT @top

    SELECT policynumbers FROM tblpolicynumbers

    SET ROWCOUNT 0

    2

    DECLARE @top INT

    SET @top = 100

    EXEC('SELECT TOP ' + @top + ' policynumbers FROM tbl')

  • Here is basically what I plan to do

    declare @MaxRecords int

    select @MaxRecords = MaxRecordsToArchive from ArchiveControl where TableName = 'PolicyProcessAudit'

    set rowcount @MaxRecords

    --Archive the top x records

    insert into dbo.PolicyProcessAudit

    select * from db..PolicyProcessAudit (nolock)

    --delete the top x records from the production table

    delete from db..PolicyProcessAudit

    set rowcount 0

    I think that would work, but wanted to run it by some others before I tested it out....

    Thanks,

    Michael

  • Put an order by on your select and your delete, or there's no guarentee that you'll get the same records. Especially since you have a nolock on the select.

    Without an order by, SQL makes no guarentees about what order rows are returned in, and hence what rows get caught in a top x

    Gail Shaw
    Microsoft Certified Master: SQL Server, MVP, M.Sc (Comp Sci)
    SQL In The Wild: Discussions on DB performance with occasional diversions into recoverability

    We walk in the dark places no others will enter
    We stand on the bridge and no one may pass

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

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