執行select into temp表,檢查表中的行數,並在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
您也可以在一個查詢中使用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
我忘了提東西。在原始發佈中查看我的編輯。你的解決方案是正確的,非常好,除了我需要返回一個狀態指示是否有太多的記錄。看來我將不得不運行第二個查詢。或者我? – AndroidDev
添加了一個臨時表版本,該版本至少返回一行包含行計數信息。 '-1'的行數太多。 –