首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何将数组传递到SQLServer存储过程?

如何将数组传递到SQLServer存储过程?
EN

Stack Overflow用户
提问于 2018-07-31 23:45:11
回答 2查看 0关注 0票数 0

如何将数组传递到SQLServer存储过程?

例如,我有一份员工名单。我想使用这个列表作为一个表,并将它与另一个表连接起来。但是,员工列表应该作为参数从C#传递。

EN

回答 2

Stack Overflow用户

发布于 2018-08-01 08:36:49

对存储过程使用表值参数。

当你从C#传入它时,将添加带有SqlDb.Structure数据类型的参数。

参考这里:http://msdn.microsoft.com/en-us/library/bb675163.aspx

例子:

代码语言:javascript
复制
// Assumes connection is an open SqlConnection object.
using (connection)
{
// Create a DataTable with the modified rows.
DataTable addedCategories =
  CategoriesDataTable.GetChanges(DataRowState.Added);

// Configure the SqlCommand and SqlParameter.
SqlCommand insertCommand = new SqlCommand(
    "usp_InsertCategories", connection);
insertCommand.CommandType = CommandType.StoredProcedure;
SqlParameter tvpParam = insertCommand.Parameters.AddWithValue(
    "@tV**ewCategories", addedCategories);
tvpParam.SqlDbType = SqlDbType.Structured;

// Execute the command.
insertCommand.ExecuteNonQuery();
}
票数 0
EN

Stack Overflow用户

发布于 2018-08-01 09:14:44

我一直在搜索关于如何将任何数组传递给sql server的所有示例和答案,而不需要创建新的表类型。我发现了这个:http://www.kodyaz.com/articles/t-sql-convert-split-delimeted-string-as-rows-using-xml.aspx,下面是如何将它应用于这个项目:

下面的代码将获得数组作为参数,并将该数组的值插入到另一个表中:

代码语言:txt
复制
Create Procedure Proc1 


@UserId int, //just an Id param
@s nvarchar(max)  //this is the array your going to pass from C# code to your Sproc

AS

    declare @xml xml

    set @xml = N'<root><r>' + replace(@s,',','</r><r>') + '</r></root>'

    Insert into UserRole (UserID,RoleID)
    select 
       @UserId [UserId], t.value('.','varchar(max)') as [RoleId]


    from @xml.nodes('//root/r') as a(t)
END 
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/-100001809

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档