dbTalk Databases Forums  

TOP v. ROWCOUNT

microsoft.public.sqlserver.programming microsoft.public.sqlserver.programming


Discuss TOP v. ROWCOUNT in the microsoft.public.sqlserver.programming forum.



Reply
 
Thread Tools Display Modes
  #1  
Old   
Mike W
 
Posts: n/a

Default TOP v. ROWCOUNT - 04-18-2005 , 02:17 PM






In the BOL for SET ROWCOUNT, it says:

"It is recommended that DELETE, INSERT, and UPDATE statements currently
using SET ROWCOUNT be rewritten to use the TOP syntax."

However, TOP Doesn't see to work with a variable.

For example,

SELECT TOP @MyNum * FROM MyTable

Is it ok to use ROWCOUNT if you have a dynamic # of rows?



Reply With Quote
  #2  
Old   
Steve Kass
 
Posts: n/a

Default Re: TOP v. ROWCOUNT - 04-18-2005 , 02:39 PM






In SQL Server 2005, you will be able to use a variable (or any expression)
if you put it in parentheses:

SELECT TOP (@MyNum) * FROM MyTable ORDER BY someColumn

For now, dynamic solutions to this require either ROWCOUNT or
clumsier techniques. Assuming you want the TOP @MyNum-many
rows in order of someColumn ASC, and someColumn is unique, these
are possibilities [untested, and the second may need a bit of
modification if there is an identity column].

select * from MyTable
where (
select count(*)
from MyTable as T
where T.someColumn < MyTable.someColumn
) <= @MyNum


-- another possibility
select top 1 * into #
from MyTable
where 1 = 0

while @MyNum > 0 begin
set @MyNum = @MyNum - 1
insert into #
select top 1 *
from MyTable
where someColumn not in (
select someColumn
from #
)
order by someColumn
end

Steve Kass
Drew University

Mike W wrote:

Quote:
In the BOL for SET ROWCOUNT, it says:

"It is recommended that DELETE, INSERT, and UPDATE statements currently
using SET ROWCOUNT be rewritten to use the TOP syntax."

However, TOP Doesn't see to work with a variable.

For example,

SELECT TOP @MyNum * FROM MyTable

Is it ok to use ROWCOUNT if you have a dynamic # of rows?



Reply With Quote
  #3  
Old   
Gert-Jan Strik
 
Posts: n/a

Default Re: TOP v. ROWCOUNT - 04-19-2005 , 12:22 PM



Yes, SET ROWCOUNT will work just fine.

Just don't forget to 'reset' it with SET ROWCOUNT 0 after the
delete/insert/update in question.

Gert-Jan


Mike W wrote:
Quote:
In the BOL for SET ROWCOUNT, it says:

"It is recommended that DELETE, INSERT, and UPDATE statements currently
using SET ROWCOUNT be rewritten to use the TOP syntax."

However, TOP Doesn't see to work with a variable.

For example,

SELECT TOP @MyNum * FROM MyTable

Is it ok to use ROWCOUNT if you have a dynamic # of rows?

Reply With Quote
Reply




Thread Tools
Display Modes

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off



Powered by vBulletin Version 3.5.3
Copyright ©2000 - 2013, Jelsoft Enterprises Ltd.