使用“Select TOP (@variable) * From”时可以指定“unlimited”吗?

Seb*_*n K 5 sql sql-server

在 SQL Server 2005 或更高版本中,您可以使用以下语法返回可变行数:

Declare @Limit Int
Set @Limit=5
Select Top(@Limit) * From TableName
Run Code Online (Sandbox Code Playgroud)

是否有一些神奇的值,您可以使用它来返回所有行?(想到这里的参数化存储过程)。设置 limit as0不会返回任何行,使用负值会产生运行时错误。

我很确定这是不可能的,但我还没有找到明确的答案。在没有If/Else阻塞的情况下完成这项工作并复制相当复杂的查询会很好。

Tan*_*ner 2

为了避免重写查询(我假设查询比问题中的 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)

  • 要复制之前删除的答案中的评论:如果正在添加一行,并且最终在您确定计数的时间和实际选择数据的时间之间添加了行,那么您将丢失一行,而不一定是刚刚添加的一个。 (3认同)