Passing an object collection as a parameter into SQL Server stored procedure

前端 未结 1 1575
面向向阳花
面向向阳花 2021-01-05 12:00

I have a general question on whether something can be done - and whether it will be the most efficient way of doing it !

To summarise: can I pass an object collectio

相关标签:
1条回答
  • 2021-01-05 12:36

    Assuming SQL Server 2008+, you can do this using a table-valued parameter. First in SQL Server create a table type:

    CREATE TYPE dbo.HobbiesTVP AS TABLE
    (
      HobbyID INT PRIMARY KEY,
      HobbyName NVARCHAR(50),
      HobbyTypeID INT
    );
    

    Then your stored procedure would say:

    @Hobbies dbo.HobbiesTVP READONLY
    

    In C# (sorry I don't know vb.net equivalent) it would be as follows (but if you just have one UserID, this doesn't need to be part of the collection, does it?):

    // as Steve pointed out, you may need to have your hobbies in a DataTable.
    
    DataTable HobbyDataTable = new DataTable();
    HobbyDataTable.Columns.Add(new DataColumn("HobbyID"));
    HobbyDataTable.Columns.Add(new DataColumn("HobbyName"));
    HobbyDataTable.Columns.Add(new DataColumn("HobbyTypeID"));
    
    // loop through objHobbyCollection and add the values to the DataTable,
    // or just populate this DataTable in the first place
    
    using (connObject)
    {
        SqlCommand cmd = new SqlCommand("dbo.User_Update", connObject);
        cmd.CommandType = CommandType.StoredProcedure;
        // other params, e.g. @UserID
        SqlParameter tvparam = cmd.Parameters.AddWithValue("@Hobbies", HobbyDataTable);
        tvparam.SqlDbType = SqlDbType.Structured;
        // ...presumably ExecuteNonQuery()
    }
    
    0 讨论(0)
提交回复
热议问题