Monthly Archives: February 2014

ROWCOUNT or TOP Clause

Beware that Rowcount is deprecated as of 2012 and TOP is the keyword suggested by BOL.
We will try to see the differences between the 2 keywords:

SET ROWCOUNT
Limits the number of records to the specified number

[cc lang=”sql”]
SET ROWCOUNT 10
select * from master..spt_values
–or
select top 10 * from master..spt_values
[/cc]

How to reset the this setting
SET ROWCOUNT 0

TOP Distinctive Features

  • TOP Can be specified with percentage
  • Can handle tied rows using WITH TIES option flag

[cc lang=”sql”]
declare @rc int
set @rc=10
select top(@rc) * from master..spt_values

or

declare @rc int
set @rc=10
set rowcount @rc
select top(@rc) * from master..spt_values
set rowcount 0
[/cc]

Disclaimer: MS suggests to avoid using ROWCOUNT in conjunction with delete, insert and update statements

Update Massive Table in smaller Batches or Transactions

[cc lang=”sql”]

SET NOCOUNT ON

DECLARE @BatchSize INT, @BatchCount INT, @totalCount INT

SET @BatchSize = 10000
SET @BatchCount = 0

SET @totalCount = (SELECT COUNT(*) FROM states)
WHILE EXISTS(SELECT * FROM states where desc like ‘%US%’)
BEGIN

UPDATE TOP (@BatchSize) states
set desc = ‘United States of America’
where desc like ‘%US%’

SET @BatchCount = @BatchCount + @@ROWCOUNT
END

SET NOCOUNT OFF

[/cc]