SQL Server How to parametrize Select top 'n' [duplicate]

pftdvrlh  于 2023-03-22  发布在  其他
关注(0)|答案(1)|浏览(122)

This question already has answers here:

Dynamic SELECT TOP @var In SQL Server (6 answers)
Closed yesterday.

I need to write a stored procedure like this but I get an error

Expecting '(', INTEGER, NUMERIC or REAL

This is my procedure code:

CREATE PROCEDURE [dbo].[myStoredProc]
    @numberOfRows int
AS
BEGIN
    SELECT TOP @numberOfRows *
    FROM dbo.myStoredProc   
END

Thank you!

juud5qan

juud5qan1#

You're very close - you just need to put the parameter value into brackets - like this:

CREATE PROCEDURE [dbo].[myStoredProc]
    @numberOfRows int
AS
BEGIN
    SELECT TOP (@numberOfRows) *
    FROM dbo.YourTableNameHere 
END

Also, you need to provide a valid table name for your FROM clause - you cannot select from the stored procedure you're just executing - that would be an endless loop in the making ....

See the official MS documentation on TOP for more details

相关问题