Jump to content

Using a @parameter within the TOP clause


Adam

Recommended Posts

Hi guys.

 

This should be a pretty straight-forward question for any T-SQL developer; how can I use a parameter passed to a stored procedure within the TOP clause of a SELECT statement?

 

For example:

 

SELECT TOP @Length * FROM vanity_urls
ORDER BY id ASC;

 

Unfortunately this produces the error: "Incorrect syntax near '@Length'".

 

Anybody have any ideas?

 

Thanks

 

Edit:

 

To add I'm using SQL Server 2005, and tried the suggestion here of wrapping the parameter in brackets, however that didn't work..?

Link to comment
Share on other sites

Cheers for all the suggestions ;)

 

Found a solution though, but it's a little hacky in that you have to set the 'rowcount' manually and declare a table variable with an auto-incrementing key.

 

Example:

 

declare @vu_temp table (
    row_count	smallint identity(1,1),
    id		    smallint,
);

insert into @vu_temp (id)
    select * from (...);

-- optional to select the total count
select count(id) as count from @vu_temp;

-- limit the number of records returned
set rowcount @LengthParameter;

select vu.* from vanity_urls vu, @vu_temp tmp
where vu.id = tmp.id
-- set the offset
and tmp.row_count >= @OffsetParameter;

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.