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 作为参数传递给存储过程
基础教程推荐
- .NET SerialPort DataReceived 事件未触发 2022-01-01
- C# 从 List<List<int>> 中删除重 2022-01-01
- 当值可以是对象或空数组时反序列化 JSON 2022-01-01
- 禁止输入少量字符,例如'<'、'&a 2022-01-01
- Moq It.Is<>不匹配 2022-01-01
- WPF 模态进度窗口 2022-01-01
- 如果有人提交恶意软件Nuget包怎么办? 2022-01-01
- 我应该在后面的代码中直接使用 Linq To SQL 还是使 2022-01-01
- Azure Functions:CosmosDBTrigger 未在 Visual Studio 中触发 2022-01-01
- 如何使用 .Net 检查 Active Directory 服务器是否已启动并正在运行? 2022-01-01
