2011-08-15 71 views
4

我需要一個臨時解決方案來解決我創建的問題。基本上我想要計算兩個值,但使用依賴於條件結果的不同方法。SQL語句中的IF子句

select userReturnval, userregisterid, OtherValue 
FROM 
(
    (SELECT otherValue 
    FROM... 
    ) as tblO --unrelated table 
    , 

    ( 
    if (select count(userregisterid) from table1 where site [email protected] and [email protected]) >0 
     SELECT userReturnval, userregisterid 
    FROM 
    (
    SELECT userReturnval, userregisterid, Rank() OVER (PARTITION BY .. ORDER BY  ...) as RANK 
      FROM ... 
      WHERE --first where clause 
     ) as tblRank 
     WHERE (RANK =1) 
    else 
     SELECT userReturnval, userregisterid 
     FROM 
     (
    SELECT userReturnval, userregisterid, Rank() OVER (PARTITION BY .. ORDER BY  ...) as RANK 
      FROM ... 
      WHERE --different where clause 
     ) as tblRank 
     WHERE (RANK =1) 

) as tblR 

我如果自己工作正常,我只是爲了讓它作爲更大的查詢的一部分工作。目前,sqlserver不喜歡如果在那裏。

希望有人能指點我正確的方向!

+0

我想這是不是您正在執行一個查詢。請確認它是存儲過程中的T-SQL? – Jaywalker

+0

是的。我帶回一個幫助對象,其中包含從數據庫中提取的多個單獨的值。在分開計算的表格之間沒有連接。 – user676767

+0

「不喜歡」是什麼意思?任何錯誤消息或只是意外的行爲?請稍微詳細一點。 –

回答

3

您可以嘗試在WHERE子句中使用case語句,如下面的語句。請注意,我認爲這不會對性能特別理想。

否則像這樣確實讓你保持它雖然單個語句:

select userReturnval, userregisterid, OtherValue 
FROM 
(
    (SELECT otherValue 
    FROM... 
    ) as tblO --unrelated table 
    , 

    ( 
    SELECT userReturnval, userregisterid 
    FROM 
    (
    SELECT userReturnval, userregisterid, Rank() OVER (PARTITION BY .. ORDER BY  ...) as RANK 
      FROM ... 
      WHERE 
       case --Choose which where clause to use 
        when (select count(userregisterid) from table1 where site [email protected] and [email protected]) >0 then 
         case when /*First where clause*/ then 1 
         else 0 
         end 
        else 
         case when /*Second where clause*/ then 1 
         else 0 
         end 
        end 
       = 1     
     ) as tblRank 
     WHERE (RANK =1) 
) as tblR 
+0

謝謝!這是實現它的方式。顯然,這只是一個臨時措施 - 我無法修補幾個星期,否則我會創建新程序並給它們打電話。再次感謝! – user676767