如何在多个字段上使用相同的参数?

时间:2019-02-26 14:09:04

标签: ms-access

我想在多个字段上使用相同的参数,因为我要从Access中提取一半数据,并从SQL Server中提取一半数据。 SQL Server表主要是Access表的克隆。所有新数据都进入SQL Server,但用户仍可以通过Access(通过ODBC数据源)与所有内容进行交互。

我正在尝试使用一些旧查询来与新的SQL Server表无缝地协同工作。基本上,它们看起来像这样:

SELECT [AccessCoolUsersTable].Name AS Name, [AccessCoolUsersTable].FavoriteSandwhich AS Sandwhich
FROM [AccessCoolUsersTable]
WHERE [AccessCoolUsersTable].FavoriteSandwhich = [Enter a Sandwhich]

我希望他们像这样运行(这是伪代码)

SELECT [AccessCoolUsersTable].Name As Name, [AccessCoolUsersTable].FavoriteSandwhich AS Sandwhich
FROM [AccessCoolUsersTable]
UNION
SELECT [SQLCoolUsersTable].Name As Name, [SLCoolUsersTable].FavoriteSandwhich AS Sandwhich
FROM [SQLCoolUsersTable]
WHERE 
    [AccessCoolUsersTable].FavoriteSandwhich = [Enter a Sandwhich]
    OR
    [SQLCoolUsersTable].FavoriteSandwhich = [Enter a Sandwhich]

但是发生的是,它首先提示输入“输入参数值[AccessCoolUsersTable].FavoriteSandwhich”,然后提示输入“输入参数值Enter a Sandwhich”。

我只是希望它一次询问该值,并将其用于[AccessCoolUsersTable].FavoriteSandwhich[SQLCoolUsersTable]。有可能吗?

1 个答案:

答案 0 :(得分:1)

您的WHERE子句必须位于“ UNION”查询中的各个查询上。另外,您需要在查询中定义参数。

PARAMETERS [Enter a Sandwhich] Text ( 255 );
SELECT [AccessCoolUsersTable].Name As Name, [AccessCoolUsersTable].FavoriteSandwhich AS Sandwhich
FROM [AccessCoolUsersTable]
WHERE [AccessCoolUsersTable].FavoriteSandwhich = [Enter a Sandwhich]
UNION
SELECT [SQLCoolUsersTable].Name As Name, [SLCoolUsersTable].FavoriteSandwhich AS Sandwhich
FROM [SQLCoolUsersTable]
WHERE [SQLCoolUsersTable].FavoriteSandwhich = [Enter a Sandwhich]

使用联合作为子查询或

PARAMETERS [Enter a Sandwhich] Text ( 255 );
SELECT a.Name, a.FavoriteSandwhich FROM
(SELECT [AccessCoolUsersTable].Name As Name, [AccessCoolUsersTable].FavoriteSandwhich AS Sandwhich
FROM [AccessCoolUsersTable]
UNION
SELECT [SQLCoolUsersTable].Name As Name, [SLCoolUsersTable].FavoriteSandwhich AS Sandwhich
FROM [SQLCoolUsersTable]) 
AS a
WHERE a.FavoriteSandwhich = [Enter a Sandwhich]

第一个查询将具有更好的性能,因为首先使用WHERE过滤结果,然后将其添加到UNION