0

我有超过 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
4

5 回答 5

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的二进制表示形式将告诉您哪些表没有记录。

于 2012-07-10T14:21:48.897 回答
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
于 2012-07-10T14:22:25.950 回答
1

You can use the EXISTS keyword to efficiently check if there is any data in a table.

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
于 2012-07-10T14:25:37.893 回答
1

(select count( ) from table1) union all (select count( ) from table2) union all (select count(*) from table3)

然后遍历结果的行

于 2012-07-10T14:23:09.643 回答
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
于 2012-07-10T14:23:16.133 回答