Sunday, September 2, 2012

How to do SELECT TOP @Param in a Stored Procedure?

Error:

I'm trying to do the following in a proc, but getting an incorrect syntax error:


SELECT TOP @NumberOfResultsToReturn * 
What am I doing wrong here? 

Solution:
This is old Method:
SET @@ROWCOUNT = @NumberOfResultsToReturnSELECT ........
SET @@ROWCOUNT = 0
This will work, although SELECT TOP (@NumberOfResultsToReturn) is preferable if you're using SQL server that supports this syntax:

New Method:
SQL Server: Put the argument in parens:
SELECT TOP (@NumberOfResultsToReturn) *


No comments: