Solved

T-SQL using CASE in the WHERE clause

Posted on 2011-02-21
3
467 Views
Last Modified: 2012-05-11
this is a simplified code sample from a stored procedure that incorporates a CASE statement in the WHERE clause.

This is part of a Search function where we can search multiple fields with one statement, based upon the value of @searchField (and where @searchTerm has the value of what needs to be found).

This approach doesn't work, what would be the correct syntax?


DECLARE
      @searchField varchar(50)
      ,@searchTerm varchar(50)

SELECT
      *
FROM
      CompanyOrders
WHERE
      (SELECT CASE
            WHEN @searchField = 'REF' THEN OrderReferenceNumber = @searchTerm
            WHEN @searchField = 'NAM' THEN OriginalCompanyName = @searchTerm
            WHEN @searchField = 'DAT' THEN CompanyFilingDate = @searchTerm    
      END)
0
Comment
Question by:conrad2010
  • 2
3 Comments
 
LVL 92

Accepted Solution

by:
Patrick Matthews earned 500 total points
ID: 34945826
DECLARE
      @searchField varchar(50)
      ,@searchTerm varchar(50)

SELECT
      *
FROM
      CompanyOrders
WHERE
      (@searchField = 'REF' AND OrderReferenceNumber = @searchTerm) OR
            (@searchField = 'NAM' AND OriginalCompanyName = @searchTerm) OR
            (@searchField = 'DAT' AND CompanyFilingDate = @searchTerm)

0
 
LVL 28

Expert Comment

by:strickdd
ID: 34945850
You can't use a CASE to determine a WHERE clause. You need to do an IF statement to separate the WHERE clauses. You can use a CASE for boolean logic in the WHERE, but it isn't recommeneded (e.g., MyCol = CASE WHEN @Filter=1 THEN @Cust ELSE Cust END).
0
 
LVL 28

Expert Comment

by:strickdd
ID: 34945857
Sorry, didn't refresh before posting.
0

Featured Post

Master Your Team's Linux and Cloud Stack

Come see why top tech companies like Mailchimp and Media Temple use Linux Academy to build their employee training programs.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

I have a large data set and a SSIS package. How can I load this file in multi threading?
This article shows gives you an overview on SQL Server 2016 row level security. You will also get to know the usages of row-level-security and how it works
Via a live example, show how to extract insert data into a SQL Server database table using the Import/Export option and Bulk Insert.
Using examples as well as descriptions, and references to Books Online, show the documentation available for datatypes, explain the available data types and show how data can be passed into and out of variables.

777 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question