How to pass table value parameters to stored procedure from .net code

后端 未结 5 2227
难免孤独
难免孤独 2020-11-22 00:35

I have a SQL Server 2005 database. In a few procedures I have table parameters that I pass to a stored proc as an nvarchar (separated by commas) and internally

5条回答
  •  故里飘歌
    2020-11-22 01:01

    The cleanest way to work with it. Assuming your table is a list of integers called "dbo.tvp_Int" (Customize for your own table type)

    Create this extension method...

    public static void AddWithValue_Tvp_Int(this SqlParameterCollection paramCollection, string parameterName, List data)
    {
       if(paramCollection != null)
       {
           var p = paramCollection.Add(parameterName, SqlDbType.Structured);
           p.TypeName = "dbo.tvp_Int";
           DataTable _dt = new DataTable() {Columns = {"Value"}};
           data.ForEach(value => _dt.Rows.Add(value));
           p.Value = _dt;
       }
    }
    

    Now you can add a table valued parameter in one line anywhere simply by doing this:

    cmd.Parameters.AddWithValueFor_Tvp_Int("@IDValues", listOfIds);
    

提交回复
热议问题