1

我创建了以下联合查询,它在大多数情况下都可以正常工作:

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];

这会在查询返回的任何内容的顶部添加“查看所有联系人”的初始行。

但是,如果它的“实际”查询部分没有返回任何结果,则整个查询不会返回任何结果,而我总是希望初始行无论如何都出现。

这是可能的,如果是这样,我做错了什么?谢谢。

编辑:谢谢大家的帮助。最终的工作查询如下,供其他需要这种东西的人参考:

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];
4

1 回答 1

1

要在 SQL 中始终返回一行数据,即使您手动提供值,您也需要从至少有一行的表中进行选择,我建议使用带有一个随机信息字段的tblDummy 。

例如:

SELECT "Hello", "Goodbye"
FROM tblDummy

作为旁注,我也会尝试摆脱:

[%$##@_Alias]

这可以通过添加别名来实现派生表

(SELECT * FROM Blah) AS A

例如将派生表命名为 A

于 2012-11-30T08:46:42.520 回答