代码之家  ›  专栏  ›  技术社区  ›  thursdaysgeek

表为空时如何返回失败

  •  1
  • thursdaysgeek  · 技术社区  · 15 年前

    使用SQL Server 2005,但仍使用DTS。我需要添加一个步骤来检查表是否是空的,如果是,不知何故会使该步骤失败。检查桌子是否是空的很容易:

    Select count(*) from source_table
    

    但是返回0也是成功的。如果是0,我希望失败(这样我可以选择不同的选项,给我们发电子邮件,跳过一些步骤)。

    3 回复  |  直到 12 年前
        1
  •  1
  •   Igor Kryltsov    12 年前
    if (select count(*) from [Table]) = 0 print 'Empty'
    
        2
  •  0
  •   Brann    15 年前

    返回-1怎么样?

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

    如果您真的想引发错误,可以使用 RAISERROR 要做到这一点:

    Declare @RowCount as bigint
    set @RowCount=count(*) from source_table
    if RowCount =0
    RAISERROR ('error message', 50000, 1)  with log
    
        3
  •  -1
  •   thursdaysgeek    15 年前

    我没有用DTS。在SSIS中解决了这个问题,但是回顾过去,我可能在DTS中做过类似的事情。

    步骤1:选择计数并将该计数保存到变量的数据流任务。选择计数需要一些工作:

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

    然后,数据流任务的输出是一个脚本组件,它是一个目标,并且有一个输入列作为该行的计数,而我的readwritevariables作为tablecount(在步骤2中用作输入的变量)。

    步骤2:计算该计数的脚本任务,如果该计数为0,则失败,否则成功。这是一条成功之路,也是一条失败之路。