对临时表进行选择,检查表中的行数并在您的选择中使用临时表或返回 0 行。
-- Your query goes here
select ID
into #T
from YourTable
--where 
-- Check the number of rows returned
if (select count(*) from #T) <= 10
begin
  -- Return the data
  select ID
  from #T
end
else
begin
  -- Don't return anything
  select ID
  from #T
  where 0 = 1
end
drop table #T
您也可以在一个查询中使用count(*) over().
select ID
from
  (
    select ID, count(*) over() as C
    from YourTable
    --where
  ) T
where C <= 10
或使用 CTE
with C as
(
  select ID
  from YourTable
  --where
)
select ID
from C
where (select count(*) from C) <= 10
选择最适合您的需求或对您的数据表现最好的任何东西。
更新
返回行数的修改后的临时表版本。
declare @MaxRows int
set @MaxRows = 25
declare @ActualRowCount int
select top(@MaxRows+1) ID
into #T
from YourTable
set @ActualRowCount = @@rowcount
if @ActualRowCount = 0
begin
  -- No rows returned
  select null as ID, 0 as [RowCount]
end
else
if @ActualRowCount > @MaxRows
begin
  -- Too many rows returned
  select null as ID, -1 as [RowCount]
end
else
begin
  -- Return rows from temp table
  select ID, @ActualRowCount as [RowCount]
  from #T
end
drop table #T