简体   繁体   中英

Using a CASE statement in the WHERE clause

I've been looking through other questions and couldn't find one like my specific situation.

I need some way to do conditional statements in my WHERE clause like the following:

If field dqpoln isn't 0, I need to add that comparison " AND dqpoln=mppoln ".

   " SELECT ... "
   " FROM ... "
   " WHERE ((dqtype=@userType AND dqssn=@userSSN) OR (dqtype=a.maagtt AND dqssn=a.maassn)) " &
   " CASE dqpoln WHEN 0 THEN '' ELSE  AND dqpoln=mppoln  END "

I've tried using a CASE statement a few different ways and tried some IF statements as well. Nothing seems to work for me.

You can try it with Boolean logic only:

(dqpoln = 0 OR dqpoln = mppoln)

Or, if you insist in using CASE , with something like:

CASE dqpoln
  WHEN 0 THEN
    mppoln
  ELSE
    dqpoln
END = mppoln

OP. I don't know if I quite understand your question. Are you saying that in a situation where dqpoln is NOT 0, then it must add the condition AND dqpoln = mppoln

The following pseudocode below should run based off of the limited knowledge we have from your question. Assuming one of those two conditions MUST hold (it's either 0, or if not, it must equal dqpoln = mpplon):

SELECT
    ...
FROM
    ...
WHERE
    (
        (dqtype=@userType AND dqssn=@userSSN) OR (dqtype=a.maagtt AND dqssn=a.maassn)
    ) AND
    (
        ((dqpoln = 0) OR (dqpoln=mppoln))
    )

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM