数据表在调用存储过程时为空
本文关键字:存储过程 调用 数据表 | 更新日期: 2023-09-27 17:49:17
我有一个存储过程,它接受一个表值参数。当我在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;
}
您需要将您创建的参数添加到命令中。
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);
}
您是否尝试过将typename添加到参数中?我很惊讶没有它也能工作。
parameter.TypeName = "NumberList";