views:

99

answers:

2

I'm trying to create a stored procedure that uses

SELECT TOP 20 * from tblRecords ....

I want the number of rows returned to be sent to the procedure as a parameter.

For some reason it says I have a syntax error near the parameter I use:

SELECT TOP @PARAM from tblRecords ....

Is there a straight way to do it or will I need to construct the Statement using String concatenations and execute it....

+3  A: 

In the stored procedure, before you do the select, issue a:

SET ROWCOUNT @param

That will limit the number of returned rows to @param.

After the query, set it back to 0:

SET ROWCOUNT 0
Andomar
what happens if I doesn't reset it back to 0 ?
Dani
Queries will @param rows until you reset it. Najmeddine's answer appears to work, that's definitely better.
Andomar
This Solution also works.
Dani
This solution is also more backwards compatible with earlier versions of SQL that did not support the TOP((@Param) syntax
JohnFx
@JohnFX: I'd not worry about backwards compat nowadays... C'mon, it's 2009 with SQL 2008 R2
gbn
+5  A: 

try :

SELECT TOP (@PARAM) * from tblRecords ....

MSDN recommends to use always parentheses, it's supported without for backward compatibility:

...For backward compatibility, TOP expression without parentheses in SELECT statements is supported, but we do not recommend this.

najmeddine
Any idea what makes this different from regular use of parameters ?
Dani
+1 You need a * after (@PARAM) btw :)
Andomar
I know, I have it in my code. I wonder why everywhere else I don't need to use () with @params....
Dani
@dani: see my edit, @Andomar: done!
najmeddine
Well, MSDN is not accurate as we can see that in select it doesn't work as well - inside a SP.
Dani
10x for the quick an enlightening response!
Dani