2013-04-25 69 views
3
string test = "SELECT count(*) FROM table where [email protected] AND [email protected]"; 

你好,是可以使用C#來檢查,如果兩個條件都爲真,或者如果只有一個是正確的?檢查SELECT語句條件爲真

int count = testCMD.ExecuteNonQuery(); 

我已經使用上面的代碼嘗試,但我不知道我的理解它是如何工作..會算爲1只,如果這兩個條件都爲真?

回答

1

嘗試:

string test = " 
    select COUNT(*) from(
     select case when (SELECT count(*) FROM table where [email protected] AND [email protected])>0 then 1 else null end Num 
     union all 
     select case when (SELECT count(*) FROM table where [email protected] OR [email protected])>0 then 1 else null end Num 
    )x where Num is not null" 

如果兩個條件都爲真,返回圖2,1,如果它們中的任何一個爲真及0如果兩個都是假的。

並使用ExecuteScalar()代替ExecuteNonQuery()(返回進行行數)。

i.e. int count = (Int32)testCMD.ExecuteScalar(); 
+0

我會嘗試這一點,回來..好像是我所期待的..謝謝 – user1737587 2013-04-25 10:03:28

+0

的ExecuteNonQuery將行的收益數量的影響,它不是值查詢返回。所以只有使用上面的Query才能解決OP問題。與ExecuteScalar方法與上面的查詢會給什麼OP想 – Damith 2013-04-25 10:06:50

+0

我接受了這個作爲回答,因爲它直接解決了我的問題..謝謝你的幫忙 – user1737587 2013-04-25 12:05:16

2

計數將返回其中兩個條件都滿足的結果數量。如果你想檢查一個或另一個,然後使用OR而不是AND。

Count

2

將計算爲1只,如果這兩個條件都爲真?

。您在查詢中使用AND運算符。

是否有可能使用C#來檢查這兩個條件是否爲真或 如果其中只有一個爲真?

通過以上查詢,。你不能。您需要可以創建兩個不同的查詢每個參數,或使用ANDOR運營商就地看到如果任一條件爲真。但與OR你不能確定哪一個是真的。

+0

感謝澄清了這一點。 – user1737587 2013-04-25 09:51:29

+0

@ user1737587,歡迎您 – Habib 2013-04-25 09:51:56