How to return a failure if a table is empty

2019-07-28 17:04发布

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).

3条回答
Melony?
2楼-- · 2019-07-28 17:32

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楼-- · 2019-07-28 17:37

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.

查看更多
唯我独甜
4楼-- · 2019-07-28 17:51
if (select count(*) from [Table]) = 0 print 'Empty'
查看更多
登录 后发表回答