November 2, 2005 at 9:20 am
Is it possible to use TOP keyword with parameter? For example, my SP has parameter @topnproduct to point how many products to return. I can use set rowcount @topnproduct. But I am just curious how to use top in the same manner? Thanks
November 2, 2005 at 10:00 am
try this
declare @sqlstring nvarchar(4000)
set @sqlstring = 'select top ' + cast(@topnproduct as varchar) + ' * from table'
exec(@sqlstring)
November 2, 2005 at 10:18 am
I know this works but as my query a bit complex I don't want to use dynamic Sql. Thanks
November 3, 2005 at 4:52 am
Unfortunately you cannot use top with a variable in SQL 2000. Most of the time, people either use set ROWCOUNT, dynamic SQL OR... You could insert the data into a temp table with an int identity(1,1) column. You can then select data where the identity column has a value <= @topNproduct.
November 3, 2005 at 7:24 am
Another great reason to upgrade to Yukon, where this is allowed.
November 3, 2005 at 7:32 am
Thanks, guys
November 3, 2005 at 9:57 am
while TOP doesn't allow a variable in SQL2000(but does in 2005) you can use rowcount instead for the same results:
drop procedure pr_search
create procedure pr_search(@limit int=0)
as
--rowcount of 0 = all,
--rowcount of 40 is obviously 40 40ws
set rowcount @limit
select name from sysobjects where xtype='U' order by name
pr_search (all tables in my db)
pr_search 12 (just 12 tables)
Lowell
November 5, 2005 at 7:11 pm
and be sure that after your select statement you set rowcount back to 0 - the ROWCOUNT setting affects inserts, updates and deletes, not just select!
So if you did
set ROWCOUNT 50
select * from myTable
delete * from myTable
Only 50 rows would be deleted
Fix would be
set ROWCOUNT 50
select * from myTable
set ROWCOUNT 0
delete * from myTable
Viewing 8 posts - 1 through 7 (of 7 total)
You must be logged in to reply to this topic. Login to reply