簡體   English   中英

如何在一個腳本中檢查多個sql表中是否存在數據?

[英]How do I check whether data is there or not in more than one sql table in one script?

我有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

您可以嘗試將表示零計數的標志相乘。 如果其中任何一個為零,則結果將為零。

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將告訴您哪些表沒有記錄。

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

從表1中選擇count( ))全部合並從表2中選擇count( ))全部(從表3中選擇count(*))

然后遍歷結果行

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

您可以使用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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM