select
  a.cucd, a.cuscd, a.spnm, a.spknm,
  a.spzip, a.spad1||a.spad2 spad, a.spcls,
  a.cshcd, b.cshnm, a.spktcd, c.ktktnm spktnm,
  a.sptel, a.spfax, a.spstp, d.cunm,
  decode(a.shflg,'1','新店','2','閉店','3','閉店予定','4','改装中','5','休眠中',null) shflgnm,
  decode(a.spcat,'02', 'DrS',
              '03', 'VS',
              '06', 'GMS',
              '05', 'ｾﾝﾀｰ',
              '01', '本部',
              '09', 'ﾈｯﾄ',
              '04', '調剤',
              '08', '個人',
              '07', 'その他' ) spcatnm,
  a.cuedi,
  a.spstp stp, decode(a.spstp,null,'inputReadOnly','inputReadOnlyStp') readcolor
from afm03 d, afm05 c, afm036 b, afm032 a
where a.cucd = b.cucd(+) and a.cshcd = b.cshcd(+)
  and a.spktcd = c.ktktcd(+)
  and a.cucd = d.cucd(+) 
  and (:ccd is null or a.cucd=:ccd)
  and (:cd is null or a.cuscd like :cd||'%')
  and (:nm is null or (upper(comnpack.MultiTOSingleBytesEx(a.spnm))
                                like '%'||upper(comnpack.MultiTOSingleBytesEx(:nm))||'%' or
                         upper(comnpack.MultiTOSingleBytesEx(a.spknm))
                                like '%'||upper(comnpack.MultiTOSingleBytesEx(:nm))||'%' or
                         upper(comnpack.MultiTOSingleBytesEx(a.spnms))
                                like '%'||upper(comnpack.MultiTOSingleBytesEx(:nm))||'%' or
                         upper(comnpack.MultiTOSingleBytesEx(a.spknms))
                                like '%'||upper(comnpack.MultiTOSingleBytesEx(:nm))||'%' or
                         upper(comnpack.MultiTOSingleBytesEx(a.spcls))
                                like '%'||upper(comnpack.MultiTOSingleBytesEx(:nm))||'%') )
  and (:zip is null or (upper(comnpack.MultiTOSingleBytesEx(a.spzip))
                                like '%'||upper(comnpack.MultiTOSingleBytesEx(:zip)||'%')) )
  and (:sadd is null or (upper(comnpack.MultiTOSingleBytesEx(a.spad1||a.spad2))
                                like '%'||upper(comnpack.MultiTOSingleBytesEx(:sadd))||'%' or
                         upper(comnpack.MultiTOSingleBytesEx(a.spkad1||a.spkad2))
                                like '%'||upper(comnpack.MultiTOSingleBytesEx(:sadd))||'%') )
  and (:tel is null or (upper(comnpack.MultiTOSingleBytesEx(a.sptel))
                                like '%'||upper(comnpack.MultiTOSingleBytesEx(:tel)||'%')) )
  and (:fax is null or (upper(comnpack.MultiTOSingleBytesEx(a.spfax))
                                like '%'||upper(comnpack.MultiTOSingleBytesEx(:fax)||'%')) )
  and (:cshcd is null or a.cshcd = :cshcd)
  and (:spcat is null or a.spcat = :spcat)
  and (:splnk is null or a.splnk = :splnk)
  and (:shflg is null or a.shflg = :shflg)
  and (:cuclcls is null or a.cuclcls = :cuclcls) /*店舗請求する/しない条件追加(検索起動時に渡す)*/
  and ((NVL(:stpflg, '0') = '1' ) or (NVL(:stpflg, '0') = '0' and a.spstp is null))
order by a.cucd, a.cuscd
