2012-07-10 14 views
0

我有超過3個sql表。如何在一個腳本中的多個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 

回答

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 

UPDATE

這可以確保所有的則至少有一個排,如果其中任何一個沒有記錄從表1

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 
+0

但是我如何知道哪個表有0值? – Neo 2012-07-10 14:23:34

+0

僅當所有表都爲空時,此查詢才返回零;當三個表中的任何**都爲空時,看起來OP正在尋找一個零。 – dasblinkenlight 2012-07-10 14:23:37

+0

@dasblinkenlight你是對的,並已更新我的答案。 OP甚至編輯了這個問題。讓我們看看最終被問到的是什麼 – codingbiz 2012-07-10 14:45:30

2

您可以嘗試乘以指示零cou的標誌nts一起。如果其中任何一個爲零,結果將爲零。

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 

的使用權力的(1,2,4,8,16,32 ,等等)作爲你的標誌。在結果的二進制表示中的一個1將告訴你哪些表沒有記錄。

+0

Waoo!直接觀看所有的剪輯,並且每個人都在單個基本查詢中添加越來越多,很好的答案 – Yaroslav 2012-07-10 14:28:36

1

(SELECT COUNT()失敗) union all (select table()from table2) union all (select count(*)fro米表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 
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 
相關問題