ICode9

精准搜索请尝试: 精确搜索
首页 > 数据库> 文章详细

SQL Server 存储过程 数组参数 (How to pass an array into a SQL Server stored procedure)

2019-09-07 15:36:12  阅读:282  来源: 互联网

标签:IDList dbo into sp tvp Server SQL ID 自定义


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
}

标签:IDList,dbo,into,sp,tvp,Server,SQL,ID,自定义
来源: https://blog.csdn.net/stoneLSL/article/details/100598296

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有