My union is being ignored in my subquery. How can I fix this?
SELECT
ab.accountnumber AS Customer#
,ob.OrderNumber AS Order#
FROM salesorderbase ob
JOIN systemuserbase su
ON su.systemuserid= ob.createdby
JOIN accountbase ab
ON ob.accountid=ab.accountid
WHERE submitstatusdescription is null
AND ob.createdon >DATEADD(dd,-1,GETDATE())
AND EXISTS
(
SELECT sopnumbe FROM cbd1.gmann.dbo.sop10101 sp
WHERE 'CRM'+substring(ob.ordernumber,5,5)
COLLATE DATABASE_DEFAULT = sp.sopnumbe
COLLATE DATABASE_DEFAULT
UNION
SELECT orignumb FROM cbd1.gmann.dbo.sop30200 sph
WHERE 'CRM'+substring(ob.ordernumber,5,5)
COLLATE DATABASE_DEFAULT = sph.sopnumbe
COLLATE DATABASE_DEFAULT
)
AND ob.statecode !=2
SELECT
ab.accountnumber AS Customer#
,ob.OrderNumber AS Order#
FROM salesorderbase ob
JOIN systemuserbase su
ON su.systemuserid= ob.createdby
JOIN accountbase ab
ON ob.accountid=ab.accountid
WHERE submitstatusdescription is null
AND ob.createdon >DATEADD(dd,-1,GETDATE())
AND EXISTS
(
SELECT sopnumbe FROM cbd1.gmann.dbo.sop10101 sp
WHERE 'CRM'+substring(ob.ordernumber,5,5)
COLLATE DATABASE_DEFAULT = sp.sopnumbe
COLLATE DATABASE_DEFAULT
UNION
SELECT orignumb FROM cbd1.gmann.dbo.sop30200 sph
WHERE 'CRM'+substring(ob.ordernumber,5,5)
COLLATE DATABASE_DEFAULT = sph.sopnumbe
COLLATE DATABASE_DEFAULT
)
AND ob.statecode !=2