2011-11-09 65 views
2

我有三個整型變量:firstCountsecondCountthirdCount。我需要比較它並輸出結果。我不擅長SQL,但是C#代碼是這樣的:比較三個變量

if(firstCount == secondCount == thirdCount) 
    return true; 
else 
    return false; 
+1

將不可能在C#中工作,並且不會在SQL工作。你需要'if(firstCount == secondCount && secondCount == thirdCount)...'。就目前來看,你正在做'((firstCount == secondCount)== thirdCount)',它的計算結果爲'(布爾真/假)== thirdCount'。 – meagar

+1

是否將零點視爲平等或不平等? –

+0

@Martin Smith不存在空值 – Wachburn

回答

2

下面是做這件事,但讀@ meagar的評論之後,我發現這個解決方案更優雅。等待他把它變成答案...

DECLARE @firstcount INTEGER 
DECLARE @secondcount INTEGER 
DECLARE @thirdcount INTEGER 

SET @firstcount = 1 
SET @secondcount = 2 
SET @thirdcount = 3 

IF @firstcount <> @secondcount SELECT 0 
ELSE IF @secondcount <> @thirdcount SELECT 0 
ELSE SELECT 1 
+0

您忘記比較@ @ firstcount到@ @countcount。 – norlando

+1

@norlando - 我沒有忘記,這是隱含的照顧。 –

+0

有沒有辦法用'select'構造來完成它?我必須將它返回給c#代碼,但不能返回到消息窗口 – Wachburn

4

單向(2008語法)。

SELECT CAST(CASE 
     WHEN COUNT(DISTINCT C) = 1 THEN 1 
     ELSE 0 
     END AS BIT) 
FROM (VALUES (@firstCount), 
       (@secondCount), 
       (@thirdCount)) t (C) 
+0

+1瞭解了一些新的東西,謝謝。 –

1

你想說如果Firstcount等於秒計數,secondcount等於第三計數返回true。

你可以做

DECLARE @a INT = 2 
DECLARE @b INT = 2 
DECLARE @c INT = 2 

IF (@a = @b AND @a = @c) 
BEGIN 
    Print('true') 
END 
ELSE 
BEGIN 
    Print('false') 
END 

雖然它沒有什麼你不差需要測試B = C因爲A = C是完全一樣的東西,因爲所有3個值必須是相同的。

3
declare @first int 
     , @second int 
     , @third int 

     select @first = 0 
      , @second = 0 
      , @third = 0 

select case when (@first = @second) AND (@second = @third) THEN 1 ELSE 0 END 
+0

+1在我個人看來,這是在可讀性和可維護性方面的最佳解決方案。 –

0

嘗試代碼,

if ((firstCount = secondCount) and (secondCount = thirdCount) and (firstCount = ThirdCount)) 
    return true; 
else 
    return false;