'Entire Union query returns no results if part of it returns no results
I've created the folllowing Union query, which works fine most of the time:
SELECT [%$##@_Alias].[Contact ID], [%$##@_Alias].[Mailing Name]
FROM (SELECT [Referrals - Contacts Within Organisations].[Contact ID], [Referrals - Contacts Within Organisations].[Mailing Name], [Referrals - Contacts Within Organisations].[Surname], [Referrals - Contacts Within Organisations].[First name]
FROM [Referrals - Contacts Within Organisations]
UNION SELECT "0" as [Contact ID], "View all contacts" as [Mailing Name], "0" as [Surname], "0" as [First name]
FROM [Referrals - Contacts Within Organisations]) AS [%$##@_Alias]
ORDER BY [%$##@_Alias].Surname, [%$##@_Alias].[First name];
This adds an initial row of "View all contacts" at the top of whatever the query returns.
However, if the "actual" query part of it returns no results, the entire query returns no results, whereas I'd always want the initial row to appear regardless.
Is this possible, and if so, what am I doing wrong? Thanks.
EDIT: Thanks all for your help. The final working query is below for reference of anyone else who needs this sort of thing:
SELECT A.[Contact ID], A.[Mailing Name]
FROM (SELECT "0" as [Contact ID], "View all contacts" as [Mailing Name], "0" as [Surname], "0" as [First name]
FROM [Dummy]
UNION
SELECT [Referrals - Contacts Within Organisations].[Contact ID], [Referrals - Contacts Within Organisations].[Mailing Name], [Referrals - Contacts Within Organisations].[Surname], [Referrals - Contacts Within Organisations].[First name]
FROM [Referrals - Contacts Within Organisations]) AS A
ORDER BY A.Surname, A.[First name];
Solution 1:[1]
To return always one row with data in SQL, even when you are manually providing the values, you need to be selecting from a table that has at least one row, I suggest using a tblDummy with one field of random information.
e.g:
SELECT "Hello", "Goodbye"
FROM tblDummy
As a side note I would also try and get rid of:
[%$##@_Alias]
This can be accomplished by aliasing your Derived tables by adding:
(SELECT * FROM Blah) AS A
for example to name the derived table as A
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Matt Donnan |