简体   繁体   中英

How to send a table-type in parameter to T-SQL while using C# IDataReader?

I wrote a t-sql sp that gets a table as parameter.

I tried to call it from c#, but didn't know what type to use:

database.AddInParameter(command, "@ID", DbType.String, id);
database.AddInParameter(command, "@TemplatesIds", DbType.WhatType??, dt);

using (IDataReader reader = database.ExecuteReader(command))
{
    while (reader.Read())
    {
    }
}

What should I use?

Since you're using a t-sql then you can use SqlDbType.Structured if you're using a SQLCommand under your (I'm guessing) IDbCommand

var dt = new DataTable();
... set up dt ...
par = new SqlParameter("@TemplatesIds", SqlDbType.Structured, dt)

There are quite a few examples of using this here on the msdn.

maybe not the best approach, but works:

-- Create the data type
CREATE TYPE dbo.PlantList AS TABLE 
(
    plant_code char(1) Not Null Primary Key
)
GO

extension method

public static class DatabaseExtensions
{
    public static void AddTableTypeParameter<T>(this Database database, DbCommand command, string name, string sqlType, IEnumerable<T> values)
    {
        var table = new DataTable();
        PropertyInfo[] members = values.First().GetType().GetProperties();
        foreach (var member in members)
        {
            table.Columns.Add(member.Name, member.PropertyType);
        }

        foreach (var value in values)
        {
            var row = table.NewRow();
            row.ItemArray = members.Select(m => m.GetValue(value)).ToArray();
            table.Rows.Add(row); 
        }
        var parameter = new SqlParameter(name, SqlDbType.Structured)
        {
            TypeName = sqlType,
            SqlValue = table
        };
        command.Parameters.Add(parameter);
    }

}

and call as follows:

database.AddTableTypeParameter(command, "@region_filter_plants", "dbo.PlantList", regionFilterPlants.Select(p => new { plant_code = p }));

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM