Adam Posted June 14, 2010 Share Posted June 14, 2010 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..? Quote Link to comment https://forums.phpfreaks.com/topic/204715-using-a-parameter-within-the-top-clause/ Share on other sites More sharing options...
Adam Posted June 14, 2010 Author Share Posted June 14, 2010 Made a grave error, I'm working from a SQL Server 2000 box. What would be the best alternative in that case then? Thanks Quote Link to comment https://forums.phpfreaks.com/topic/204715-using-a-parameter-within-the-top-clause/#findComment-1071772 Share on other sites More sharing options...
Adam Posted June 17, 2010 Author Share Posted June 17, 2010 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; Quote Link to comment https://forums.phpfreaks.com/topic/204715-using-a-parameter-within-the-top-clause/#findComment-1073395 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.