Passing parameter of type 'object' in table-valued parameter for sql_variant column

前端 未结 3 1992
遥遥无期
遥遥无期 2021-01-08 00:29

I have a table-valued parameter in SQL Server 2012 defined as:

CREATE TYPE [dbo].[TVP] AS TABLE (
    [Id] [int] NOT NULL,
    [FieldName] [nvarchar](100) NO         


        
3条回答
  •  暖寄归人
    2021-01-08 00:58

    This post is many years old now but I hit the same problem and have a solution. If you do not use a DataTable but instead populate a collection of SqlDataRecord then you can set the datatype of the SqlDataRecord to SqlDbType.Variant.

     List dataTable = new List();
    var dr = new SqlDataRecord(
                                new SqlMetaData("Id", SqlDbType.Int),
                                new SqlMetaData("Value", SqlDbType.Variant));
    
    dr.SetInt32(0, id);
    dr.SetValue(1, myObject);
    
    dataTable.Add(dr);
    
    [...]
    
    SqlCommand sqlCommand = new SqlCommand("dbo.MyProc");
    var structuredParam = sqlCommand.Parameters.Add("myTableParam", SqlDbType.Structured);
    structuredParam.Value = dataTable;
    

提交回复
热议问题