【问题标题】:How to use a sql table-valued parameter to filter results?如何使用 sql 表值参数过滤结果?
【发布时间】:2013-11-07 02:27:49
【问题描述】:

我正在尝试创建一个使用table-valued parameter 过滤导入名称的存储过程。我们得到一个导入的名称列表,需要返回一个名称列表,这些名称要么不存在于数据库中,要么已经收到特定类型的消息。

我遇到困难的部分是如何创建连接。带有 IS NULL 检查的左外连接适用于单个表检查,但我不确定是否有两个表。任何帮助将不胜感激。谢谢!

我正在使用 MS SQL 2012。带有列的表:

Recipients: 
id | name 

SendResults:
id | recipientid | type

测试

CREATE PROCEDURE [dbo].[usp_RecipientsSendCheck]
(
     @Type int 
    ,@RecipientsImports dbo.RecipientsImport READONLY
)
AS
BEGIN

    SELECT i.Name FROM @RecipientsImports i

    LEFT JOIN Recipients r
    ON i.Name = r.Name

    LEFT JOIN SendResults s
    ON s.RecipientId = r.id 

    WHERE r.Name IS NULL OR Type <> @Type

END

用户定义的表类型

CREATE TYPE [dbo].[RecipientsImport] AS TABLE(
    [Name] [nchar](10) NOT NULL
)

【问题讨论】:

    标签: sql sql-server stored-procedures


    【解决方案1】:

    类似这样的:

    create procedure [dbo].[usp_RecipientsSendCheck]
    (
        @Type int,
        @RecipientsImports dbo.RecipientsImport READONLY
    )
    as
    begin
        select i.Name
        from @RecipientsImports as i
            left outer join Recipients as r on r.Name = i.Name
            left outer join SendResults as s on s.RecipientId = r.id and s.[Type] = @Type
        where
            r.Name is null or
            s.id is not null
    end
    

    【讨论】:

    • 感谢您的快速回复。出于某种原因,您的更改不包括 Recipients 表中的名称并且具有不同类型的 SendResults 记录。知道为什么吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-21
    • 1970-01-01
    • 2021-03-22
    • 2022-01-03
    • 2013-01-13
    • 1970-01-01
    • 2015-07-30
    相关资源
    最近更新 更多