如何在一个脚本中检查多个sql表中是否存在数据?

时间:2012-07-10 14:16:32

标签: sql sql-server sql-server-2008

我有超过3个sql表。

现在我正试图从所有牌桌select count(*)但我该怎么做?

我想知道所有表格中是否存在数据

I need to check the row count from previous business day ~15% for any table and it sends an email alert

我试过以下请帮我完成

PROCEDURE [dbo].[SendEmail_WSOTableDataAlert]
AS
BEGIN

declare @err int
IF NOT EXISTS (select 1 from T1) OR
NOT EXISTS (select 1 from T2)
BEGIN
set @error=1
END

//here i need to show which table is having empty data how can i do this please help

SET @tableHTML = @tableHTML +  +
            '</TABLE>' + @EmailFooter;



@error =1

then

发送邮件

END

5 个答案:

答案 0 :(得分:2)

您可以尝试将指示零计数的标记相乘。如果其中任何一个为零,则结果为零。

select (case when (select count(*) from table1)=0 then 0 else 1 end
      *case when (select count(*) from table2)=0 then 0 else 1 end
      *case when (select count(*) from table3)=0 then 0 else 1 end) as no_zeros

如果您想知道哪个表具有全零,您可以按如下方式转换查询:

select (case when (select count(*) from table1)=0 then 1 else 0 end
      +case when (select count(*) from table2)=0 then 2 else 0 end
      +case when (select count(*) from table3)=0 then 4 else 0 end
      +case when (select count(*) from table4)=0 then 8 else 0 end) as no_zeros

使用2的幂(1,2,4,8,16,32等)作为标志。结果的二进制表示中的1将告诉您哪些表没有记录。

答案 1 :(得分:2)

Select 
    case when count(*) = 0 then 
        'No rows' 
    else 
        'Has rows'
    end 
FROM
(
   Select * from @table1
   UNION ALL
   Select * from @table2
   UNION ALL
   Select * from @table3
) t

<强>更新

这确保所有行至少有一行,如果其中任何一行没有记录

则失败
Select 
    case when count(*) = 0 then 
        'No rows' 
    else 
        'Has rows'
    end 
FROM
(
   Select top 1 1 found from @table1
   intersect
   Select top 1 1 found from @table2
   intersect
   Select top 1 1 found from @table3
) t

答案 2 :(得分:1)

(从table1中选择count()) 联合所有 (从表2中选择计数()) 联合所有 (从表3中选择计数(*))

然后遍历结果行

答案 3 :(得分:1)

declare @count1 int 
select @count1 = count(*)
from table1

declare @count2 int 
select @count2 = count(*)
from table2

declare @count3 int 
select @count3 = count(*)
from table3

if (@count1 + @count2 + @count3 = 0)
    --do something
else 
    --do something else

答案 4 :(得分:1)

您可以使用EXISTS关键字有效地检查表格中是否有任何数据。

IF NOT EXISTS (SELECT 1 FROM Table1) OR NOT EXISTS (SELECT 1 FROM Table2) OR NOT EXISTS (SELECT 1 FROM Table3) 
BEGIN
   /* do something */
END