如何基于变量值 SQL Server 2019 包含/排除相交查询的部分内容

问题描述 投票:0回答:1

我编写了几个表值函数 (TVF),它们查询连接表以获取与主记录表具有特定关联的 recordID 列表。

然后,我有一个存储过程查询,它在 WHERE 子句中使用 (TVF) 的 UNION 或 INTERSECT 来返回要在主查询中处理的 recordID 的完整列表。

declare @att1 int = NULL
declare @att2 int = NULL
select recordID
    , title
    , trackingNumber
from record
where recordID in (
   select * from searchAtt1(@att1)
   UNION
   select * from searchAtt2(@att2)
   )

传入 NULL 值适用于 UNION 部分,因为并集是两者的组合集(返回的列表包括具有 att1 或 att2 的所有记录。

我传递什么值才能允许 INTERSECT 返回包含 att1 和 att2 的正确记录集。为其中一个变量传入 ZERO (0) 或 NULL 会返回一个空集,因为相应的联结表中没有具有 0 或 NULL 值的记录。

declare @att1 int = NULL
declare @att2 int = NULL
select recordID
    , title
    , trackingNumber
from record
where recordID in (
   select * from searchAtt1(@att1)
   INTERSECT
   select * from searchAtt2(@att2)
   )

如果值未传递给 SP 或者值为 0 或 NULL,是否有办法绕过其中一个 TVF 调用?

sql-server stored-procedures sql-server-2019
1个回答
0
投票

试试这个

declare @att1 int = NULL
declare @att2 int = NULL
select recordID
    , title
    , trackingNumber
from record
where recordID in (
   select * from searchAtt1(case when @att1 is not null then @att1 else @att2 end)
   INTERSECT
   select * from searchAtt2(case when @att2 is not null then @att2 else @att1 end)
   )
© www.soinside.com 2019 - 2024. All rights reserved.