views:

48

answers:

2

I need to query some data. here is the query that i have constructed but which isn't workig fine for me. For this example I am using AdventureWorks database.

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

This is not working for me. How can I have multiple where condition clauses in the THEN of the the same CASE? How can I make this work?

A: 

It's not a cut and paste. The CASE expression must return a value, and you are returning a string containing SQL (which is technically a value but of a wrong type). This is what you wanted to write, I think:

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

I also suspect that this might not work in some dialects, but can't test now (Oracle, I'm looking at you), due to not having booleans.

However, since @url is not dependent on the table values, why not make three different queries, and choose which to evaluate based on your parameter?

Amadan
Thanks Amadan. I am using SQL Server and this query doesn't work fine. It throws a syntax error. CASE statement cannot be used like this I presume. I had tried this and because there was a syntax error, I tried to construct the where clause as a string (As i posted in the question earlier), but a little thought and I can make out its wrong but I am not sure how to make it right.
Pavanred
+2  A: 

Another way based on 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 '%'+@ur+'%') 
END
Patrick Säuerl
Makes me wonder why I was trying to do this only by using CASE statement. I guess I can use this to construct the query as I need. thanks
Pavanred
It´s basically:condition 1or condition 2or condition 3or (!condition1 and !condition2 and !condition3 and condition 4)No problem =)
Patrick Säuerl