2017-05-24 75 views
1

我目前正在嘗試編碼可以返回TRUE,FALSE或NEITHER的SQL搜索。雖然我目前的代碼有效,但我不喜歡我必須複製和粘貼大量代碼的事實,並且想知道是否有辦法在此處減少代碼量。SQL,搜索true,false或同時搜索

DECLARE @FYear int = 2017 
DECLARE @FQuarter char(2) = 'Q2' 
DECLARE @FINANCIAL_GOAL_MET bit = NULL 

IF(@FINANCIAL_GOAL_MET IS NULL) 
    SELECT FYear, 
      FQuarter, 
      IIF(FINANCIAL_GOAL_MET = 'TRUE', 1,0) AS Financial_Goal_Met 
    FROM Finances  
    WHERE (FYear = @FYear) 
      AND (FQuarter = @FQuarter) 
ELSE 
    SELECT FYear, 
      FQuarter, 
      IIF(FINANCIAL_GOAL_MET = 'TRUE', 1,0) AS Financial_Goal_Met 
    FROM Finances 
    WHERE (FYear = @FYear) 
      AND (FQuarter = @FQuarter) 
      AND FINANCIAL_GOAL_MET = @FINANCIAL_GOAL_MET 
+0

只需使用底部的查詢和變化'和FINANCIAL_GOAL_MET = @ FINANCIAL_GOAL_MET'爲'AND FINANCIAL_GOAL_MET = @FINANCIAL_GOAL_MET或@FINANCIAL_GOAL_MET = NULL' – scsimon

+1

TSQL沒有boolead數據類型 - bit數據類型將保持爲0,1或null,但不是「true」或「false」。 –

回答

2

您可以在一個查詢做到這一點:

DECLARE @FYear int = 2017; 
DECLARE @FQuarter char(2) = 'Q2'; 
DECLARE @FINANCIAL_GOAL_MET bit = NULL; 

SELECT FYear, FQuarter, 
     (CASE WHEN FINANCIAL_GOAL_MET = 'TRUE' THEN 1 ELSE 0 
     END) AS Financial_Goal_Met 
FROM Finances f 
WHERE (FYear = @FYear) AND (FQuarter = @FQuarter) AND 
     (@FINANCIAL_GOAL_MET IS NULL OR FINANCIAL_GOAL_MET = @FINANCIAL_GOAL_MET); 

對於那些不熟悉SQL Server中的bit類型,'TRUE'被接受的比較,即使它是一個字符串。

+0

謝謝你的訣竅 – AWinter