2

I'm having trouble getting an if then statement to work in the following query:

define start_date = '&START_DATE'
define end_date   = '&END_DATE'
define co_cd      = '&COMPANY_CODE'
define myacct     = '&4_DIGIT_ACCOUNT'

select ivc.pmt_dt, ivc.ivc_cd, gl.seq#, gl.gl_acct_cd, ivc.ve_cd, ve.ve_name, gl.amt
from ivc ivc
  left outer join ve ve
    on ivc.ve_cd = ve.ve_cd
  left outer join ivc$gl_acct gl
    on (ivc.ivc_cd = gl.ivc_cd and ivc.ve_cd = gl.ve_cd)
where ivc.post_dt >= '&start_date'
  and ivc.post_dt <= '&end_date'
  and substr(gl_acct_cd,1,4) = '&myacct'
  and if '&co_cd' = 'BSD' then
        substr(gl_acct_cd,6,2) in ('04','08','11','31','37')
      elseif '&co_cd' = 'JEYE' then
        substr(gl_acct_cd,6,2) in ('03','20','21','22','23','24')
      elseif '&co_cd' = 'BSF' then
        --something
      elseif '&co_cd' = 'ALL' then
        --something
      else
        substr(gl_acct_cd,6,2) in '&co_cd'
      end if
order by gl.amt desc

What am I doing wrong on the If Then statement? I keep getting an invalid relational operator error. I've searched quite a bit online but cannot find an answer. Any help is appreciated. I know enough to be dangerous with this stuff...do quite a bit of sql queries but they typically don't get too complicated. Thanks!

4

2 回答 2

3

With SQL being set-oriented, there isn't really a procedural method like IF.

Instead, structure the query like this:

and (
  ('&co_cd' = 'BSD'  and substr(gl_acct_cd,6,2) in ('04','08','11','31','37')) or
  ('&co_cd' = 'JEYE' and substr(gl_acct_cd,6,2) in ('03','20','21','22','23','24')) or
  ('&co_cd' = 'BSF'  and --something) or
  ('&co_cd' = 'ALL'  and --something) or
  ('&co_cd' not in ('BSD','JEYE','BSF','ALL') and substr(gl_acct_cd,6,2) in '&co_cd'))
于 2013-05-20T17:55:58.140 回答
2

If then else will not work in SQL statements you should use CASE WHEN but in your case, case when is not good option try this

and (
      ('&co_cd' = 'BSD' and substr(gl_acct_cd,6,2) in ('04','08','11','31','37'))
      OR 
      ('&co_cd' = 'JEYE' and substr(gl_acct_cd,6,2) in ('03','20','21','22','23','24'))
      OR 
      ('&co_cd' = 'BSF' and --something)
      OR 
      ('&co_cd' = 'ALL' and --something)
      OR
      ('&co_cd' NOT IN ('BSD','JEYE','BSF', 'ALL') and substr(gl_acct_cd,6,2) in '&co_cd')
     )
于 2013-05-20T17:56:30.587 回答