【问题标题】:Checking multiple columns have any of multiple values in a Table value parameter检查多个列在表值参数中具有多个值中的任何一个
【发布时间】:2020-09-16 07:38:50
【问题描述】:

我正在尝试创建一个查询来帮助从现有数据库中获取帐户列表。我将通过 C# 中的两个表值参数 (TVP) 传入两个整数列表。然后我需要查看多个列是否具有相应 TVP 表中的任何值。整数的 TVP 列表由不同的客户端提供,并且可能因客户端而异。这就是为什么它们是 TVP 允许将值作为参数传入的原因。

数据结构无法更改,它是基于来自另一个系统的数据创建的。有关更改数据结构的评论将无济于事。为了提供帮助,我将讨论一个示例表,以帮助显示我需要什么。

查看如下表格:

Table Accounts
  varchar(200) AccountId
  int StatusId1
  int StatusId2
  int StatusId3
  int StatusId4
  int Identifier1
  int Identifier2
  int Identifier3
  int Identifier4
  int Identifier5

我知道我可以做这样的 sql 语句:

Select AccountId from Accounts where StatusId1 In (1,2,3)

我了解到我也可以反转 In 命令:

Select AccountId from Accounts where 1 In (StatusId1, StatusId2, StatusId3, StatusId4)

这只让我检查每一列的一个值。问题是我需要在将 TVP 用于整数列表时将两者混合。

我能够创建的最接近的是以下内容:

--Load the TVP lists 
SELECT * INTO #StatusCodes FROM @StatusId
SELECT * INTO #IdentityCodes FROM @IdentifierId

--Find the Accounts that have the chosen Ids
SELECT AccountId
FROM Accounts
WHERE StatusId1 IN( SELECT Id FROM #StatusCodes)
OR StatusId2 IN( SELECT Id FROM #StatusCodes)
OR StatusId3 IN( SELECT Id FROM #StatusCodes)
OR StatusId4 IN( SELECT Id FROM #StatusCodes)
OR Identifier1 IN (SELECT Id FROM #IdentityCodes)
OR Identifier2 IN (SELECT Id FROM #IdentityCodes)
OR Identifier3 IN (SELECT Id FROM #IdentityCodes)
OR Identifier4 IN (SELECT Id FROM #IdentityCodes)
OR Identifier5 IN (SELECT Id FROM #IdentityCodes)

这个查询在我的原型中有效,我得到了至少具有这些 ID 之一的帐户列表。我看到很多选择语句,看起来不太好。我也不确定它的性能如何。我想知道是否有更好的方法来做到这一点?

这适用于根据我们客户的条件创建报告的系统。每个客户每晚都会运行一对到 100 份报告。这意味着这可能每晚运行数百次。虽然它不是一个每小时运行数千次的系统,但它确实处理了大量数据。它将搜索的一些数据库将很大,需要搜索很多帐户。

【问题讨论】:

    标签: c# sql sql-server tsql join


    【解决方案1】:

    一个选项使用exists

    select a.acountId
    from accounts a
    where 
        exists (
            select 1 
            from #StatusCodes s 
            where s.id in (a.StatusId1, a.StatusId2, a.StatusId3, a.StatusId4)
        )
        or exists (
            select 1 
            from #IdentityCodes i 
            where i.id in (a.Identifier1, a.Identifier2, a.Identifier3, a.Identifier4)
        )
    

    【讨论】:

    • 我能够在我的测试项目中重新创建它。查询效果很好。它看起来比我创建的查询更好。我还能够使用测试数据库在我的测试应用程序中运行一些时间。此查询每次运行得更快。谢谢。
    猜你喜欢
    • 2015-10-03
    • 1970-01-01
    • 2012-12-04
    • 1970-01-01
    • 1970-01-01
    • 2015-07-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多