Inconsistent results in a query with a UNION clause - missing records in result set

I created a query in SQL Server (2005) that includes a UNION clause.  If I run each of the queries separately (without a UNION) the provide the expected results.  When I run the query with the UNION clause the query executes (without errors or warnings)  I get results EXCEPT that I 'lose' records from the generated results set.

In writing the query I paid  particular attention to field data types to make sure they matched.  In the second query there is no Inner Join on the two tables - this was done be design so as not to lose certain records.

Any thoughts/consideration when doing this type of query?

Here is the syntax:

SELECT MatterID, MatterInfoMatterNum, MatterInfoSortName, ClientInfoClientID, TBankAllocInfoStatus, TBankAllocInfoCheckID, TBankAllocInfInvDate, TBankAllocInfoAmount, TBankAllocInfoEntryType, TBankAllocInfActivityID, TBankAllocInfExplanation, TBankCommInfStatus, TBankCommInfDate, TBankCommInfEntryType, TBankCommInfAmount, TBankCommInfPaidTo, ActivityCodesNickname, ActivityCodesName
 FROM   ((MattInf MattInf INNER JOIN TBAlloc TBAlloc ON MattInf.MatterID=TBAlloc.MatterID) INNER JOIN ActCode ActCode ON TBAlloc.TBankAllocInfActivityID=ActCode.ActivityCodesID) INNER JOIN TBComm TBComm ON TBAlloc.TBankAllocInfoCheckID=TBComm.TBankCommInfSequenceID
UNION
SELECT MatterID, MatterInfoMatterNum, MatterInfoSortName, ClientInfoClientID,
0 as TBankAllocInfoStatus, null as TBankAllocInfoCheckID, 0 asTBankAllocInfInvDate,
0 as TBankAllocInfoAmount, 0 as TBankAllocInfoEntryType, 0 as TBankAllocInfActivityID,
‘ ‘ as TBankAllocInfExplanation, 0 as TBankCommInfStatus, 0 as TBankCommInfDate,
0 as TBankCommInfEntryType, 0 as TBankCommInfAmount, ‘ ‘ as TBankCommInfPaidTo,
ActCode.ActivityCodesNickname, ActCode.ActivityCodesName
 FROM   MattInf, ActCode

Thanks for your input.

John
JRStpeteAsked:
Who is Participating?

[Webinar] Streamline your web hosting managementRegister Today

x
 
arufusConnect With a Mentor Commented:
if you are checking the record count and concluding that records are lost, probably this could be just a Illusion. Union actuallly performs a Distinct operation after executing both the queries, so that any records that are matched in the first query is skipped from the second query. In case you want all rows including the duplicate records try using UNION ALL

0
 
Raja Jegan RSQL Server DBA & ArchitectCommented:
You are missing a JOIN condition in your Second SELECT query of UNION statement.
And use UNION ALL if duplicate records are filtered because of UNION.
0
 
JRStpeteAuthor Commented:
Don't know how I missed that! Perfect
0
All Courses

From novice to tech pro — start learning today.