Solved

SQL server conditional case statement in where clause using IN clause

Posted on 2014-07-23
6
944 Views
Last Modified: 2014-07-25
Hi,
I have a situation where I need to filter based on a variable that is being set on a webpage, and if the variable isn't set, then I have to filter based on a comma-delimited string to see if there's a match.
Here it is:
First, I build the comma delimited string, with a STUFF in the FROM clause of the select statement - as follows:
 outer apply
 (
 select
  STUFF
  (
   (    
    select distinct
     ', ' + dx.class
FROM
data_RECORDS sr
 Join data_Xref dx ON sr.Text = dx.text
WHERE sr.userid = @vUID
    order by
     ', ' + dx.class
    for xml path ('')
   ),
   1,
   2,
   ''
  )
 ) mg (Classes)

mg.Classes now contains a long string, comma delimited, of the various classes for this particular user (@Vuid)

Now I want to add an additional condition to the WHERE clause I want to do the filtering.
If a variable with a class name was selected on the input screen, I only want to include that particular class.
If the variable from the input screen is NULL or '', then I want to include all classes from mg.Classes, and I want to filter out the classes that are not part of that string.
I tried many things in the WHERE clause, and they aren't working.
Even though the value of string is correct (it's a comma-delimited string of classes), the WHERE clause does not like the "IN" and is returning an error (Incorrect syntax near the keyword 'CASE'.)

How can I filter to see if the class in the table is in the list of allowed classes that was returned by the STUFF.

Here's a sample:
 WHERE dx.CLASS IN
       (      CASE
      
             when @vClass is NULL
                  then '(' + mg.Classes + ')'
            when @vClass = '' then '(' + mg.Classes + ')'
ELSE @vClass  END )
            
This is complicated, but any help would be GREATLY appreciated!
0
Comment
Question by:avivap
  • 2
  • 2
  • 2
6 Comments
 
LVL 48

Accepted Solution

by:
PortletPaul earned 500 total points
ID: 40216114
If you are you generating the query through something like C#/PHP or similar then using comma separated strings can work - but you need to supply more of the script generating that sql.

as it looks right now you won't get valid sql syntax from that case expression.

---
Despite the fact that A comma separated string looks like an IN() statement, it isn't. It is still ONE string.

if mg.Classes looks: just,like,this,separated,series

when actually being assessed it is treated as a 'single value'

WHERE dx.CLASS IN( 'just,like,this,separated,series' )

and 'just' or 'like' or 'this' or 'separated' or 'series' will not match to any part of  'just,like,this,separated,series'

Could you not use something like this?
 WHERE 
        ( 
         (@vClass is NULL OR @vClass = '') AND dx.CLASS  IN ( 
                                                    select dx.class FROM data_RECORDS sr
                                                    Join data_Xref dx ON sr.Text = dx.text 
                                                    WHERE sr.userid = @vUID         
                                                 ) 
         )
OR 
        ( 
         (@vClass is NOT NULL OR @vClass <> '') AND dx.CLASS = @vClass
         )

Open in new window

0
 
LVL 32

Expert Comment

by:ste5an
ID: 40216171
Think relational and atomic. Thus don't look in the resulting string, but in the raw data. Otherwise you may use an approach like
WHERE   ( COALESCE(@vClass, '') != ''
          AND mg.Classes LIKE '%' + dx.CLASS + '%'
        )
        OR ( COALESCE(@vClass, '') = ''
             AND @vClass = dx.CLASS
           )

Open in new window


But this requires a sligthly different class string. But this leads to the question, why concatenating the values first and searching the result and not in the raw data?
0
 

Author Comment

by:avivap
ID: 40218184
HI.
Thanks for your quick response!
Portletpaul - I tried your solution - and it works.  The only issue is that it takes a lot longer to run, I'm imagining it's because of the additional select in the WHERE clause.  Any ideas regarding optimizing?

Ste5an - I haven't tried yours because you wrote 'But this requires a slightly different class string' - would you mind explaining further?

I'm waiting to hear back from both of you.
Thanks.
0
Enabling OSINT in Activity Based Intelligence

Activity based intelligence (ABI) requires access to all available sources of data. Recorded Future allows analysts to observe structured data on the open, deep, and dark web.

 
LVL 48

Expert Comment

by:PortletPaul
ID: 40218274
consider indexing these:

dx.class
sr.Text
dx.text
sr.userid  

and in general that statistics are kept up to date and that  indexes are maintained

You can try 'select distinct' in that small subquery it might help (or it might not) I cannot be certian
0
 
LVL 32

Expert Comment

by:ste5an
ID: 40218729
The condition mg.Classes LIKE '%' + dx.CLASS + '%' works only when your class names are not reused as partial name. E.g. the classes Red and CadmiumRed. In the case of the class Red we could get an condition like 'CadmiumRed LIKE '%Red%', which is a false positive. This could be avoided by using ',' + mg.Classes + ',' LIKE '%,' + dx.CLASS + ',%', as concrete expression ',CadmiumRed,' LIKE '%,Red,%'. Now it works under the constraint that no comma is allowed in the content of the atomic class values.
0
 

Author Closing Comment

by:avivap
ID: 40220435
Thank you both for your help!
0

Featured Post

PRTG Network Monitor: Intuitive Network Monitoring

Network Monitoring is essential to ensure that computer systems and network devices are running. Use PRTG to monitor LANs, servers, websites, applications and devices, bandwidth, virtual environments, remote systems, IoT, and many more. PRTG is easy to set up & use.

Join & Write a Comment

Ever needed a SQL 2008 Database replicated/mirrored/log shipped on another server but you can't take the downtime inflicted by initial snapshot or disconnect while T-logs are restored or mirror applied? You can use SQL Server Initialize from Backup…
Ever wondered why sometimes your SQL Server is slow or unresponsive with connections spiking up but by the time you go in, all is well? The following article will show you how to install and configure a SQL job that will send you email alerts includ…
Via a live example, show how to extract information from SQL Server on Database, Connection and Server properties
Viewers will learn how to use the SELECT statement in SQL and will be exposed to the many uses the SELECT statement has.

707 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

Need Help in Real-Time?

Connect with top rated Experts

11 Experts available now in Live!

Get 1:1 Help Now