简体   繁体   English

如何在使用C#IDataReader时将表类型参数发送到T-SQL?

[英]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. 我写了一个t-sql sp,它将一个表作为参数。

I tried to call it from c#, but didn't know what type to use: 我试图从c#调用它,但不知道使用什么类型:

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 因为你正在使用t-sql然后你可以使用SqlDbType.Structured如果你在你的(我猜)IDbCommand下使用SQLCommand

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. 在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 }));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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