SQL Server 存储过程 数组参数 (How to pass an array into a SQL Server stored procedure)
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了SQL Server 存储过程 数组参数 (How to pass an array into a SQL Server stored procedure),小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1633字,纯文字阅读大概需要3分钟。
内容图文
Resource from StackOverflow
使用存储过程,如何传递数组参数?
1.分割解析字符串,太麻烦
2.添加Sql Server 自定义类型 sp_addtype
问题需求:需要向SP 传递数组类型的参数
select * from Users where ID IN (1,2,3 )
Sql Server 数据类型 并没有数组,但是允许自定义类型,通过 sp_addtype
添加 一个自定义的数据类型,可以允许c# code 向sp传递 一个数组类型的参数
但是不能直接使用 sp_addtype,而是需要结构类型的数据格式,如下:
CREATE TYPE dbo.IDList
AS TABLE
(
ID INT
);
GO
有点像个是一个临时表,一种对象,这里只加了ID
在sp 中可以声明自定义类型的参数
CREATE PROCEDURE [dbo].[DoSomethingWithEmployees]
@IDList AS dbo.IDList readonly
Example
1. First, in your database, create the following two objects
CREATE TYPE dbo.IDList
AS TABLE
(
ID INT
);
GO
CREATE PROCEDURE [dbo].[DoSomethingWithEmployees]
@IDList AS dbo.IDList readonly
AS
SELECT * FROM [dbo].[Employees]
where ContactId in
( select ID from @IDList )
RETURN
2. In your C# code
// Obtain your list of ids to send, this is just an example call to a helper utility function
int[] employeeIds = GetEmployeeIds();
DataTable tvp = new DataTable();
tvp.Columns.Add(new DataColumn("ID", typeof(int)));
// populate DataTable from your List here
foreach(var id in employeeIds)
tvp.Rows.Add(id);
using (conn)
{
SqlCommand cmd = new SqlCommand("dbo.DoSomethingWithEmployees", conn);
cmd.CommandType = CommandType.StoredProcedure;
SqlParameter tvparam = cmd.Parameters.AddWithValue("@List", tvp);
// these next lines are important to map the C# DataTable object to the correct SQL User Defined Type
tvparam.SqlDbType = SqlDbType.Structured;
tvparam.TypeName = "dbo.IDList";
// execute query, consume results, etc. here
}
内容总结
以上是互联网集市为您收集整理的SQL Server 存储过程 数组参数 (How to pass an array into a SQL Server stored procedure)全部内容,希望文章能够帮你解决SQL Server 存储过程 数组参数 (How to pass an array into a SQL Server stored procedure)所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。