期望的结果行数作为存储过程中的参数

Eri*_*ham 2 sql sql-server parameters stored-procedures

我想允许我的使用者指定他们想要在存储过程中返回的行数.我想模仿这种行为:

SELECT  TOP 100 AccountId ,
        AccountName
FROM    dbo.Account
Run Code Online (Sandbox Code Playgroud)

但是以这种方式:

DECLARE @resultCount INT = 100;

SELECT  TOP @resultCount AccountId ,
        AccountName
FROM    dbo.Account
Run Code Online (Sandbox Code Playgroud)

当然第二个版本导致"@resultCount附近的语法不正确"错误.有没有办法做到这一点,而不分解为连接SQL字符串和使用EXEC?我发现这不是很难维护.

KM.*_*KM. 9

添加括号( )围绕@resultCount:

DECLARE @resultCount INT = 100;

SELECT  TOP (@resultCount) AccountId ,
        AccountName
FROM    dbo.Account
Run Code Online (Sandbox Code Playgroud)