c# - 如何为存储过程中的 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 端是什么样子的呢?如果我要传递类别“工具”、“硬件”和条件“新”、“使用”。
我该怎么做?
解决方案
要将 3 个进一步的参数添加到您的 SP、, @Qty
&@Category
您@Condition
只需复制您已经采取的步骤。
- 创建任何其他用户定义的表类型
两者都@Category
需要@Condition
一个 UDT,@Qty
而不是因为它是本机类型。
@Category
有些人会更喜欢为和分别使用一个单独的 UDT @Condition
,个人认为它们都采用相同的数据类型,我创建了一个通用实用程序 UDT,例如
CREATE TYPE [dbo].[udt_ShortString] AS TABLE
(
[Value] [varchar](128) NULL
)
- 修改 SP 例如
CREATE PROCEDURE [dbo].[usp_DoSomethingWithTableTypedParameter]
(
@UserIdList udt_UserId READONLY
, @CategoryList udt_ShortString READONLY
, @ConditionList udt_ShortString READONLY
, @Qty int
)
AS
- 将值添加到您的
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 });
注意:为了清楚起见,我已经硬编码了参数名称和类型名称 - 你当然可以像你所做的那样自由地将它们作为变量传递。
推荐阅读
- sql - 医院数据库:查找出现在多个健康记录上的健康卡号实例
- java - Java中的多线程(并行代码比串行慢得多)
- c# - 使用 flurl 时 ASP.NET Web API 可能的反序列化问题
- list - SML:如何判断一个列表索引是否为空?
- javascript - 使用 parseFloat 将用户输入作为在 JavaScript 中添加在一起的字符串返回
- javascript - 本地存储持久文本区域不起作用
- javascript - 在 Javascript 中查找模式的最简单方法
- powerbi - 计算的四分位数
- javascript - 为什么这个函数会破坏我数组中的值?
- javascript - Express / Passport SAML 身份验证重定向导致无限循环