Binding empty list or null value to table valued p

2020-05-18 04:46发布

I have created a stored procedure that takes a table valued parameter that is a table with a single column of type int. The idea is to simply pass a list of ids into the store procedure and allow the sp to work with the data. However, in the case where there is no data to pass in, I am encountering problems (things work correctly when I have data). I am converting a List to an IEnumerable, and binding that to the table valued parameter for the sp. I have tried to bind an empty List, which resulted in the error

System.ArgumentException: There are no records in the SqlDataRecord enumeration. To send a table-valued parameter with no rows, use a null reference for the value instead.

I then tried to bind a null value (which I thought was what the above message was getting at), but that only resulted in a different error message

System.NotSupportedException: DBNull value for parameter '@MainItemIdList' is not supported. Table-valued parameters cannot be DBNull.

It does not appear that you can declare the table valued parameter as nullable in the sp declaration. What is the correct method for binding an empty list to at table valued parameter?

4条回答
在下西门庆
2楼-- · 2020-05-18 04:55

I get the error when passing an empty IEnumerable<int> but it works fine when I pass an empty List<int> instead.

查看更多
Root(大扎)
3楼-- · 2020-05-18 05:02

Not passing a value does work but not in the case where I had multiple table value parameters to pass into the procedure. How I solved it was to specify a value of DEFAULT in my query string. For example,

string sqlQuery = "[dbo].[GetOrderData] @QueueId";

if (OrderIdList.Any())
{
    sqlQuery = sqlQuery + ", @OrderIdList";
}
else
{
    sqlQuery = sqlQuery + ", DEFAULT";
}

if (RegionIdList.Any())
{
    sqlQuery = sqlQuery + ", @RegionIdList";
}
else
{
    sqlQuery = sqlQuery + ", DEFAULT";
}

Kudos to http://www.sommarskog.se/arrays-in-sql-2008.html#Invoking where I found the solution for this.

查看更多
别忘想泡老子
4楼-- · 2020-05-18 05:06

The trick is: don’t pass in the parameter at all. The default value for a table-valued parameter is an empty table.

It is a shame that the exception message is so unhelpful.

查看更多
Anthone
5楼-- · 2020-05-18 05:10

I was a bit confused by what the 'not passing the parameter' statement means. What ends up working for Entity Framework ExecuteSqlCommandAsync() is this:

  new SqlParameter("yourParameterName", SqlDbType.Structured)
  {
      Direction = ParameterDirection.Input,
      TypeName = "yourUdtType",
      Value = null
  };

This will pass the parameter as 'default'.

查看更多
登录 后发表回答