2010-06-13 166 views
4

我需要查詢一些數據。這裏是我構建的查詢,但這對我來說並不合適。對於這個例子我使用AdventureWorks數據庫。帶CASE語句的多個條件

SELECT * FROM [Purchasing].[Vendor] WHERE PurchasingWebServiceURL LIKE 
case 
// In this case I need all rows to be returned if @url is '' or 'ALL' or NULL 
when (@url IS null OR @url = '' OR @url = 'ALL') then ('''%'' AND PurchasingWebServiceURL IS NULL') 
//I need all records which are blank here including nulls 
     when (@url = 'blank') then (''''' AND PurchasingWebServiceURL IS NULL') 
//n this condition I need all record which are not like a particular value 
     when (@url = 'fail') then ('''%'' AND PurchasingWebServiceURL NOT LIKE ''%treyresearch%''') 
//Else Match the records which are `LIKE` the input value 
     else '%' + @url + '%' 
    end 

這不適合我。如何在同一CASETHEN中有多個條件條款?我該如何做這項工作?

回答

4

基於amadan另一種方式:

SELECT * FROM [Purchasing].[Vendor] WHERE 

     ((@url IS null OR @url = '' OR @url = 'ALL') and PurchasingWebServiceURL LIKE '%') 
    or 

     (@url = 'blank' and PurchasingWebServiceURL = '') 
    or 
     (@url = 'fail' and PurchasingWebServiceURL NOT LIKE '%treyresearch%') 
    or((@url not in ('fail','blank','','ALL') and @url is not null and 
      PurchasingWebServiceUrl Like '%'[email protected]+'%') 
END 
+0

讓我想知道爲什麼我只是通過使用CASE語句來嘗試這樣做。我想我可以用它來構建查詢,因爲我需要。感謝 – pavanred 2010-06-13 19:13:01

+0

It's基本上是:(!!!條件1和條件2和condition3和條件4) 條件1 或條件2 或狀況3 或 沒有問題=) – kamahl 2010-06-13 20:15:57

4

這不是剪切和粘貼。 CASE表達式必須返回一個值,並返回一個包含SQL的字符串(這在技術上是一個值,但類型錯誤)。這是你想寫什麼,我想:

SELECT * FROM [Purchasing].[Vendor] WHERE 
CASE 
    WHEN @url IS null OR @url = '' OR @url = 'ALL' 
    THEN PurchasingWebServiceURL LIKE '%' 
    WHEN @url = 'blank' 
    THEN PurchasingWebServiceURL = '' 
    WHEN @url = 'fail' 
    THEN PurchasingWebServiceURL NOT LIKE '%treyresearch%' 
    ELSE PurchasingWebServiceURL = '%' + @url + '%' 
END 

我也懷疑,這可能不是在某些方言的工作,但現在不能測試(甲骨文,我看着你),由於不有布爾人。

但是,由於@url不依賴於表值,所以爲什麼不做三個不同的查詢,並根據您的參數選擇要評估哪個?

+1

感謝Amadan。我正在使用SQL Server,並且此查詢無法正常工作。它會引發語法錯誤。 CASE聲明不能像我所假定的那樣使用。我試過這個,因爲有語法錯誤,我試圖構造where子句作爲一個字符串(正如我在前面發佈的問題),但有一點想法,我可以做出它的錯誤,但我不知道如何改正它。 – pavanred 2010-06-13 19:08:32