避免在特定条件下返回结果集

And*_*Dev 6 sql t-sql

我执行一个select语句.如果结果集中的行数小于或等于某个数字,则返回所选行.如果行数大于某个数字,我想不返回任何行.

运行select并进行比较后,如果行数大于允许的行数,我执行:

SELECT TOP 0 NULL AS ID
Run Code Online (Sandbox Code Playgroud)

我发现的是,最初选择的两个记录也与第二个结果集一起返回,其中一个列名为ID,没有记录.显然,初始select语句仍然被返回,我想避免这种情况.有什么办法吗?

编辑:忘了添加我需要返回一个状态值,指示是否有更多的行比允许的行.这意味着我必须得到计数,并且更愿意拥有计数,而不必两次运行相同的查询.因此,如果允许的最大行数为25但实际存在零行,则返回状态为0.但是如果行数大于25,那么我不会返回任何行,但我将状态设置为 - 1.

Mik*_*son 5

将select选择到临时表中,检查表中的行数,并在select中使用temp表或返回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
Run Code Online (Sandbox Code Playgroud)

您也可以在一个查询中使用count(*) over().

select ID
from
  (
    select ID, count(*) over() as C
    from YourTable
    --where
  ) T
where C <= 10
Run Code Online (Sandbox Code Playgroud)

或者使用CTE

with C as
(
  select ID
  from YourTable
  --where
)
select ID
from C
where (select count(*) from C) <= 10
Run Code Online (Sandbox Code Playgroud)

选择最适合您需求的产品或使用您的数据做到最好.

更新
返回行计数的修改临时表版本.

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
Run Code Online (Sandbox Code Playgroud)