在 SQL Server 2005 或更高版本中,您可以使用以下语法返回可变行数:
Declare @Limit Int
Set @Limit=5
Select Top(@Limit) * From TableName
Run Code Online (Sandbox Code Playgroud)
是否有一些神奇的值,您可以使用它来返回所有行?(想到这里的参数化存储过程)。设置 limit as0不会返回任何行,使用负值会产生运行时错误。
我很确定这是不可能的,但我还没有找到明确的答案。在没有If/Else阻塞的情况下完成这项工作并复制相当复杂的查询会很好。
为了避免重写查询(我假设查询比问题中的 SQL 更复杂),您可以返回行计数来替换特定情况下的变量,例如,如果变量 = 0,则返回全部:
declare @Limit Int
set @Limit = 0
if @Limit = 0
// get the row count from the table you are querying if @Limit = 0
select @Limit = count(1) from TABLE_NAME
// then use the value in your query as before
select top(@Limit) * from TABLE_NAME
Run Code Online (Sandbox Code Playgroud)