首页 > 解决方案 > 如何为存储过程中的 in 子句传递参数?

问题描述

我将如何获取存储过程中的这个查询并传递正确的参数?

select * from Inventory
where category in (@categories) and qty > @qty and condition in (@conditions)

我看到我应该做这样的事情

CREATE PROCEDURE [dbo].[usp_DoSomethingWithTableTypedParameter]
(
    @categories categories READONLY
    @Qty int,
    @conditions
)

但是 ADO.NET 端是什么样子的呢?如果我要传递类别“工具”、“硬件”和条件“新”、“使用”。

我该怎么做?

标签: c#sqlsql-server

解决方案


要将 3 个进一步的参数添加到您的 SP、, @Qty&@Category@Condition只需复制您已经采取的步骤。

  1. 创建任何其他用户定义的表类型

两者都@Category需要@Condition一个 UDT,@Qty而不是因为它是本机类型。

@Category有些人会更喜欢为和分别使用一个单独的 UDT @Condition,个人认为它们都采用相同的数据类型,我创建了一个通用实用程序 UDT,例如

CREATE TYPE [dbo].[udt_ShortString] AS TABLE
(
    [Value] [varchar](128) NULL
)
  1. 修改 SP 例如
CREATE PROCEDURE [dbo].[usp_DoSomethingWithTableTypedParameter]
(
    @UserIdList udt_UserId READONLY
    , @CategoryList udt_ShortString READONLY
    , @ConditionList udt_ShortString READONLY
    , @Qty int
)
AS
  1. 将值添加到您的command对象,您在其中加载新数据表与您已经加载现有 userId 表完全相同,例如
cmd.Parameters.Add(new SqlParameter("@UserIdList", System.Data.SqlDbType.Structured) { TypeName = "udt_UserId", Value = userIdList });
cmd.Parameters.Add(new SqlParameter("@CategoryList", System.Data.SqlDbType.Structured) { TypeName = "udt_ShortString", Value = categoryList });
cmd.Parameters.Add(new SqlParameter("@ConditionList", System.Data.SqlDbType.Structured) { TypeName = "udt_ShortString", Value = conditionList });
cmd.Parameters.Add(new SqlParameter("@Qty", SqlDbType.Int) { Value = qty });

注意:为了清楚起见,我已经硬编码了参数名称和类型名称 - 你当然可以像你所做的那样自由地将它们作为变量传递。


推荐阅读