如何将数组传递到SQLServer存储过程?
例如,我有一份员工名单。我想使用这个列表作为一个表,并将它与另一个表连接起来。但是,员工列表应该作为参数从C#传递。
发布于 2018-08-01 08:36:49
对存储过程使用表值参数。
当你从C#传入它时,将添加带有SqlDb.Structure数据类型的参数。
参考这里:http://msdn.microsoft.com/en-us/library/bb675163.aspx
例子:
// 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();
}
发布于 2018-08-01 09:14:44
我一直在搜索关于如何将任何数组传递给sql server的所有示例和答案,而不需要创建新的表类型。我发现了这个:http://www.kodyaz.com/articles/t-sql-convert-split-delimeted-string-as-rows-using-xml.aspx,下面是如何将它应用于这个项目:
下面的代码将获得数组作为参数,并将该数组的值插入到另一个表中:
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
https://stackoverflow.com/questions/-100001809
复制相似问题