Results 1 to 11 of 11

Thread: Using WHERE CASE in SP

  1. #1
    Fanatic Member
    Join Date
    Jul 07
    Posts
    617

    Using WHERE CASE in SP

    Hi, Im using SP with 2 parameters named @criteria and @value. The @criteria serve as column flag in which column to perform the search eg Supplier and Invoice No and the @value which is the query value.
    It seems CASE has the flexibility to meet the requirement but didnt work for me.

    <code>
    select column1
    from myview
    where
    case when (@criteria='a') then
    column1=@value
    else
    column2=@value
    end
    </code>

    Thanks in advance.
    Learn something new every .001 second.

  2. #2
    Unmoderated abhijit's Avatar
    Join Date
    Jun 99
    Location
    Chit Chat Forum.
    Posts
    3,117

    Re: Using WHERE CASE in SP

    It looks like you want to create your sql statement dynamically.
    Do a search for dynamic SQL and hopefully that will help you.

    Also, what database are you using? SQL Server or Oracle?


    Everything that has a computer in will fail. Everything in your life, from a watch to a car to, you know, a radio, to an iPhone, it will fail if it has a computer in it. They should kill the people who made those things.- 'Woz'
    save a blobFileStreamDataTable To Text File

  3. #3
    Fanatic Member
    Join Date
    Jul 07
    Posts
    617

    Re: Using WHERE CASE in SP

    Hi abhijit, that was an option I consider but I found something interesting and its looks very promising. It does work when I test but not sure with the performance though compare to dynamic sql.


    select column1
    from myview
    where
    case @criteria
    when 'a' then case column1=@value then 1 else 0 end
    when 'b' then case column2=@value then 1 else 0 end
    end=1


    BTW Im SQL 2005 dev.
    Learn something new every .001 second.

  4. #4
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 04
    Location
    CT
    Posts
    14,406

    Re: Using WHERE CASE in SP

    That's not a good idea - do this instead

    Code:
    If @criteria='a'
    Begin
         select column1 
         from myview 
         where column1=@value 
    End
    Else
    Begin
         If @criteria='b'
         Begin
              select column1 
              from myview 
              where column2=@value 
         End
    End
    Creating a "super-conditional" based SELECT statement makes no sense. It does not run any faster (probably slower) - is a nightmare to modify later...

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  5. #5
    PowerPoster techgnome's Avatar
    Join Date
    May 02
    Posts
    21,636

    Re: Using WHERE CASE in SP

    I don't know about that... I've had good success with constructs like this:
    Code:
    where 
      case 
        when @Criteria = 'a' and ((Column1 = @SomeValue) or (Column2 = @SomeValue)) then 1
        else 0
      end = 1

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.-I also subscribe to all threads I participate, so there's no need to pm when there's an update.*
    *Proof positive that searching the forums does work: View Thread *
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *
    * Use Offensive Programming, not Defensive Programming. * On Error Resume Next is error ignoring, not error handling(tm).
    "There is a major problem with your code, and VB wants to tell you what it is.. but you have decided to put your fingers in your ears and shout 'I'm not listening!'" - si_the_geek on using OERN

  6. #6
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 04
    Location
    CT
    Posts
    14,406

    Re: Using WHERE CASE in SP

    I live by the rule that CASE should be avoided in a WHERE clause. Pretty much just to keep the execution plans "more sql-standard".

    Look at this simple pair of queries - and the attached execution plan - as you can see the first one does a INDEX SEEK (good) - the second does an INDEX SCAN (not so good). Notice the INDEX SCAN is twice as "costly" as the SEEK. If the fields involved are not in an index it's most likely going to do a TABLE SCAN (really, really not so good).

    Code:
    Select * From Concept_T Where CId between 10 and 20
    
    Select * From Concept_T Where Case When CId between 10 and 20 Then 1 Else 0 End=1
    Attached Images Attached Images  

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  7. #7
    Fanatic Member
    Join Date
    Jul 07
    Posts
    617

    Re: Using WHERE CASE in SP

    Hi szlamany, appreciate the comment. Does it mean if I have compound criteria I need to write it 4 (four) times?

    Code:
    if @criteria1= x
    Begin
       If @criteria2=x1
           Begin
           End
       else
           Begin
           End
    End
    else
       If @criteria2=x1
           Begin
           End
       else
           Begin
           End
    Learn something new every .001 second.

  8. #8
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 04
    Location
    CT
    Posts
    14,406

    Re: Using WHERE CASE in SP

    Yes - it would mean you write logic for four spots.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  9. #9
    Hirsute Mumbler FunkyDexter's Avatar
    Join Date
    Apr 05
    Location
    An obscure body in the SK system. The inhabitants call it Earth
    Posts
    2,412

    Re: Using WHERE CASE in SP

    I've often heard the "No Case in a Where clause" argument and have always accepted it at face value.

    Just wondering, though, why not have this entirely handled in the Where clause but using Ands and Ors rather than Cases:-

    Code:
    Select Blah
    From BlahTable
    Where (@Criteria = 'a' and Column1 = @Value)
    OR (@Criteria = 'b' and Column2 = @Value)
    OR (@Criteria = 'c' and Column3 = @Value)
    etc
    That would seem like a more "set based" aproach to me where as ifs and elses feel more "procedural". I've done absolutely zero performance testing around that though.
    When one of my minions says, "Hey, he's just one guy, what can he do?" I say "This"... and shoot them.

    The problem with putting your lair in a volcano is keeping your robot army from melting.

    I know that the human being and the fish can coexist peacefully - George Bush

  10. #10
    MS SQL Powerposter szlamany's Avatar
    Join Date
    Mar 04
    Location
    CT
    Posts
    14,406

    Re: Using WHERE CASE in SP

    @funky - I've often used the method you indicate - just a standard WHERE clause with proper use of OR's to handle the major conditional differences.

    Although - when the "very fields" you are going to be using for "evaluation" are "conditional" I can see having separate SELECT's.

    I also find myself - for the purposes of large SPROCS returning data for reporting - setting up a TEMP TABLE or TABLE VARIABLE with PRIMARY KEY's to include. I can massage and manipulate that TEMP TABLE several times before arriving at the SINGLE SELECT at the bottom of the SPROC that pulls FROM #TEMPTABLE and JOIN's in all the others.

    *** Read the sticky in the DB forum about how to get your question answered quickly!! ***

    Please remember to rate posts! Rate any post you find helpful - even in old threads! Use the link to the left - "Rate this Post".

    Some Informative Links:
    [ SQL Rules to Live By ] [ Reserved SQL keywords ] [ When to use INDEX HINTS! ] [ Passing Multi-item Parameters to STORED PROCEDURES ]
    [ Solution to non-domain Windows Authentication ] [ Crazy things we do to shrink log files ] [ SQL 2005 Features ] [ Loading Pictures from DB ]

    MS MVP 2006, 2007, 2008

  11. #11
    Hirsute Mumbler FunkyDexter's Avatar
    Join Date
    Apr 05
    Location
    An obscure body in the SK system. The inhabitants call it Earth
    Posts
    2,412

    Re: Using WHERE CASE in SP

    Although - when the "very fields" you are going to be using for "evaluation" are "conditional" I can see having separate SELECT's
    Ok, I can certainly see that from a readibility and maintenance perspective. Are you aware of any performance implications to either aproach? I just want to make sure I'm not missing a trick.

    Personally I use my aproach just because it's valid for just about any query. I don't want to have performance tune every single query I write so I just aim for a consistent aproach and then tune anything that's problematic. But I always want to know if there's a known exception case I can accomodate instead of waiting to fix it after the event.
    When one of my minions says, "Hey, he's just one guy, what can he do?" I say "This"... and shoot them.

    The problem with putting your lair in a volcano is keeping your robot army from melting.

    I know that the human being and the fish can coexist peacefully - George Bush

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •