Passing DataTable to stored procedure as an argument(将 DataTable 作为参数传递给存储过程)
问题描述
我有一个用 C# 创建的数据表.
I have a data table created in C#.
DataTable dt = new DataTable();
dt.Columns.Add("Name", typeof(string));
dt.Columns.Add("Age", typeof(int));
dt.Rows.Add("James", 23);
dt.Rows.Add("Smith", 40);
dt.Rows.Add("Paul", 20);
我想把它传递给下面的存储过程.
I want to pass this to the following stored procedure.
CREATE PROCEDURE SomeName(@data DATATABLE)
AS
BEGIN
INSERT INTO SOMETABLE(Column2,Column3)
VALUES(......);
END
我的问题是:我们如何将这 3 个元组插入 SQL 表?我们是否需要使用点运算符访问列值?还是有其他方法可以做到这一点?
My question is : How do we insert those 3 tuples to the SQL table ? do we need to access the column values with the dot operator ? or is there any other way of doing this?
推荐答案
您可以更改存储过程以接受 表值参数作为输入.但是,首先,您需要创建一个与 C# DataTable 的结构相匹配的用户定义表 TYPE:
You can change the stored procedure to accept a table valued parameter as an input. First however, you will need to create a user defined table TYPE which matches the structure of the C# DataTable:
CREATE TYPE dbo.PersonType AS TABLE
(
Name NVARCHAR(50), -- match the length of SomeTable.Column1
Age INT
);
调整您的 SPROC:
Adjust your SPROC:
CREATE PROCEDURE dbo.InsertPerson
@Person dbo.PersonType READONLY
AS
BEGIN
INSERT INTO SomeTable(Column1, Column2)
SELECT p.Name, p.Age
FROM @Person p;
END
在C#中,将数据表绑定到PROC参数时,需要将参数指定为:
In C#, when you bind the datatable to the PROC parameter, you need to specify the parameter as:
parameter.SqlDbType = SqlDbType.Structured;
parameter.TypeName = "dbo.PersonType";
另请参阅此处的示例 传递表格-存储过程的有值参数
这篇关于将 DataTable 作为参数传递给存储过程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:将 DataTable 作为参数传递给存储过程


基础教程推荐
- 首先创建代码,多对多,关联表中的附加字段 2022-01-01
- 将事件 TextChanged 分配给表单中的所有文本框 2022-01-01
- 从 VS 2017 .NET Core 项目的发布目录中排除文件 2022-01-01
- 在 VS2010 中的 Post Build 事件中将 bin 文件复制到物 2022-01-01
- 是否可以在 asp classic 和 asp.net 之间共享会话状态 2022-01-01
- 全局 ASAX - 获取服务器名称 2022-01-01
- 错误“此流不支持搜索操作"在 C# 中 2022-01-01
- 如何动态获取文本框中datagridview列的总和 2022-01-01
- 经典 Asp 中的 ResolveUrl/Url.Content 等效项 2022-01-01
- JSON.NET 中基于属性的类型解析 2022-01-01