Home > Database > Mysql Tutorial > How to Pass Table-Valued Parameters to Stored Procedures using ADO.NET?

How to Pass Table-Valued Parameters to Stored Procedures using ADO.NET?

Barbara Streisand
Release: 2025-01-11 10:57:42
Original
1027 people have browsed it

How to Pass Table-Valued Parameters to Stored Procedures using ADO.NET?

Using ADO.NET to Pass Table-Valued Parameters to Stored Procedures

Table-valued parameters provide a streamlined method for passing datasets to stored procedures. This guide demonstrates how to implement this functionality within ADO.NET.

1. Defining a User-Defined Table Type in SQL Server

First, create a user-defined table type within your SQL Server database to serve as the structure for your table-valued parameter:

<code class="language-sql">CREATE TYPE [dbo].[MyDataType] As Table
(
    ID INT,
    Name NVARCHAR(50)
)</code>
Copy after login

2. Stored Procedure Creation

Next, create a stored procedure that accepts this user-defined table type as a parameter:

<code class="language-sql">CREATE PROCEDURE [dbo].[MyProcedure]
(
    @myData [dbo].[MyDataType] READONLY
)
AS
BEGIN
    SELECT * FROM @myData
END</code>
Copy after login

3. DataTable Construction in C#

In your C# code, build a DataTable to mirror the structure of your SQL Server table type:

<code class="language-csharp">DataTable myDataTable = new DataTable("MyDataType");
myDataTable.Columns.Add("Name", typeof(string));
myDataTable.Columns.Add("Id", typeof(int));
myDataTable.Rows.Add("XYZ", 1);
myDataTable.Rows.Add("ABC", 2);</code>
Copy after login

4. SqlParameter Configuration

Finally, create a SqlParameter object and configure it to represent your table-valued parameter:

<code class="language-csharp">SqlParameter parameter = new SqlParameter();
parameter.ParameterName = "@myData";
parameter.SqlDbType = System.Data.SqlDbType.Structured;
parameter.TypeName = "[dbo].[MyDataType]"; // Specify the type name
parameter.Value = myDataTable;
command.Parameters.Add(parameter);</code>
Copy after login

By following these steps, you can efficiently pass table-valued parameters to your stored procedures using ADO.NET. Remember to replace [dbo].[MyDataType] with the actual name of your user-defined table type.

The above is the detailed content of How to Pass Table-Valued Parameters to Stored Procedures using ADO.NET?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template