如何使用sql表值参数来过滤结果?

时间:2013-11-06 18:14:50

标签: sql sql-server stored-procedures

我正在尝试创建一个使用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
)

1 个答案:

答案 0 :(得分:4)

这样的事情:

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