DataTable在调用存储过程

时间:2015-05-14 15:30:06

标签: c# sql-server stored-procedures

我有一个存储过程,它接受一个表值参数。当我使用SQL Server Management Studio 2014中的表值参数测试过程时,我得到了正确的值。

declare @NumberList as dbo.NumberList

insert into @NumberList(value) values (16101197);
insert into @NumberList(value) values (16101196);
insert into @NumberList(value) values (16101194);
insert into @NumberList(value) values (16101042);
insert into @NumberList(value) values (16101190);
insert into @NumberList(value) values (16101191);

--select value from @NumberList

exec GetClientLeadsByClientId @NumberList

但是,在我的C#代码中,DataTable为空。我在SQL Server Management Studio中测试时,clientIds匹配上述值。

private DataTable GetClientLeadsByClientIds(List<int> clientIds)
{
    var dataTable = new DataTable();
    var numberList = AddClientIdsToNumberListTemporaryTable(clientIds);
    var connection = new SqlConnection(ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString);
    using (var command = new SqlCommand("GetClientLeadsByClientId", connection) { CommandType = CommandType.StoredProcedure } )
    using (var dataAdapter = new SqlDataAdapter(command))
    {
        var parameter = new SqlParameter();
        parameter.ParameterName = "@NumberList";
        parameter.SqlDbType = SqlDbType.Structured;
        parameter.Value = numberList;
        dataAdapter.Fill(dataTable);
    }

    return dataTable;
}

我使用此方法创建表值参数。

private DataTable AddClientIdsToNumberListTemporaryTable(List<int> clientIds)
{
    var dataTable = new DataTable("NumberList");
    dataTable.Columns.Add("value", typeof(int));
    for (int i = 0; i < clientIds.Count; i++)
    {
        dataTable.Rows.Add(clientIds[i]);
    }

    return dataTable;
}

2 个答案:

答案 0 :(得分:2)

您需要将您创建的参数添加到命令中。

using (var dataAdapter = new SqlDataAdapter(command))
{
    var parameter = new SqlParameter();
    parameter.ParameterName = "@NumberList";
    parameter.SqlDbType = SqlDbType.Structured;
    parameter.Value = numberList;

    //ADD THIS
    command.Parameters.Add(parameter);

    dataAdapter.Fill(dataTable);
}

答案 1 :(得分:0)

您是否尝试过将typename添加到参数中?如果没有它,我会感到惊讶。

parameter.TypeName = "NumberList";