How to return a failure if a table is empty

2019-07-28 16:51发布

问题:

Using SQL Server 2005, but still using DTS. I need to add a step to check if a table is empty, and somehow fail the step if it is. It's easy checking if the table is empty:

Select count(*) from source_table

But returning 0 is a success, too. If it is 0, I want a failure (so that I can fork to a different option, email us, skip some steps).

回答1:

if (select count(*) from [Table]) = 0 print 'Empty'


回答2:

what about returning -1 ?

Select 
   case when count(*)>=0 then count(*) else -1 end 
from 
   source_table

If you really want to raise an error, you can use RAISERROR to do just that :

Declare @RowCount as bigint
set @RowCount=count(*) from source_table
if RowCount =0
RAISERROR ('error message', 50000, 1)  with log


回答3:

I didn't use DTS. It was resolved in SSIS, although, looking back, I could have probably done something similar in DTS.

Step 1: A data flow task that selects count and saves that count to a variable. The select count took a bit of work:

select cast(count(*) as integer) as Row_Count from MyTable

and then the output of the data flow task was a script component that was a destination and had an input column as that ROW_COUNT, and my ReadWriteVariables as TableCount (the variable that was used as input in step 2)

Step 2: A script task that evaluates that count and fails if the count was 0, succeeds otherwise. Forking from this is a success route and a failure route.