Make a selection in the temp table, check the number of rows in the table and use the temp table in your selections or return 0 rows.
-- 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
You can also do this in a single query with count(*) over()
.
select ID from ( select ID, count(*) over() as C from YourTable
Or using CTE
with C as ( select ID from YourTable --where ) select ID from C where (select count(*) from C) <= 10
Choose everything that best suits your needs or best fulfills your data.
Update
A modified version of the temp table that returns the number of rows.
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
source share