⌘BABAKOV.NET Let's code!
100% [dark] [ru]

Passing a dataset to MSSQL from C# in one query

Often there is a need to pass a set of data to a procedure at once, in this publication, an example of how to do this in C# for the MSSQL database will be given.

We will use the usual way of calling a procedure without any frameworks.

First, let's create a test table in the database:

SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[Bottles](
	[Uid] [uniqueidentifier] NOT NULL,
	[Name] [varchar](50) NULL,
	[Color] [varchar](50) NULL
) ON [PRIMARY]
GO

In this table, we will place bottles of different names and colors (just for testing).

Now let's create a user-defined table type data, which we will pass to the procedure:

CREATE TYPE [dbo].[BottleColorType] AS TABLE(
[Name] [varchar](50) NULL,
[Color] [varchar](50) NULL
)
GO

Exactly these data we will pass to the procedure.

Now let's write a very simple test procedure:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

ALTER PROCEDURE [dbo].[GetBottleColors] 

@DataList as dbo.BottleColorType readonly
AS
BEGIN
SET NOCOUNT ON;

declare @res as bit;
set @res = 1;

insert into Bottles (Uid, Name, Color)
    select 
newid() as Uid,
d.[Name] as Name,
d.[Color] as Color

from @DataList d;

select @res as Result;
END

This procedure will insert the received table data into the table Bottles

The database is now prepared, it remains only to write the code to call the procedure in C#:

using System;
using System.Data;
using System.Data.SqlClient;

namespace TestProcTable
{
    class Program
    {
        static void Main(string[] args)
        {
            Console.WriteLine("Передаем табличку в процедуру");

            // Создаем таблицу для передачи в БД (идентичную типу BottleColorType)
            DataTable table = new DataTable();
            table.Columns.Add("Name", typeof(string));
            table.Columns.Add("Color", typeof(string));

            // Заполняем в таблицу пару записей
            DataRow row = table.NewRow();
            row["Name"] = "Ессентуки";
            row["Color"] = "Зелёный";
            table.Rows.Add(row);

            row = table.NewRow();
            row["Name"] = "ХанКуль";
            row["Color"] = "Белый";
            table.Rows.Add(row);

            // Выполняем запрос к БД
            bool res = SendTableToBaseProc(table);

            Console.WriteLine(
                res ? "Запрос выполнен успешно" : "Запрос не выполнен"
                );

            Console.ReadKey();
        }

        /// <summary>
        /// Процедура выполняющая запрос к БД с передачей таблицы в качестве параметра
        /// </summary>
        /// <param name="table"></param>
        /// <returns></returns>
        public static bool SendTableToBaseProc(DataTable table)
        {
            bool result = false;
            try
            {
                using (SqlConnection con = new SqlConnection("Server=ервер;Database=test;User Id=логин;Password=пароль;"))
                {
                    // Выполняем процедуру
                    using (SqlCommand cmd = new SqlCommand("[dbo].[GetBottleColors]", con))
                    {
                        cmd.CommandType = CommandType.StoredProcedure;

                        // Добавляем таблицу как параметр
                        SqlParameter p_list = new SqlParameter
                        {
                            ParameterName = "@DataList",
                            SqlDbType = SqlDbType.Structured,
                            Direction = ParameterDirection.Input,
                            Value = table
                        };
                        cmd.Parameters.Add(p_list);

                        con.Open();
                        SqlDataReader reader = cmd.ExecuteReader();
                        if (reader.HasRows)
                        {
                            while (reader.Read())
                            {
                                result = reader.GetBoolean(reader.GetOrdinal("Result"));
                            }

                        }
                        reader.Close();
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
            }
            return result;
        }
    }
}

And that's it.

After executing the given code, 2 records from the passed table will be inserted into the Bottles table in the database.

Comments (0)

No comments yet.

Leave a comment
Comment
Images (up to 5 MB)
Your comment will appear after moderation.