How to pass an array into a SQL Server stored procedure

前端 未结 11 2619
轻奢々
轻奢々 2020-11-21 23:28

How to pass an array into a SQL Server stored procedure?

For example, I have a list of employees. I want to use this list as a table and join it with another table.

11条回答
  •  孤街浪徒
    2020-11-21 23:48

    Use a table-valued parameter for your stored procedure.

    When you pass it in from C# you'll add the parameter with the data type of SqlDb.Structured.

    See here: http://msdn.microsoft.com/en-us/library/bb675163.aspx

    Example:

    // Assumes connection is an open SqlConnection object.
    using (connection)
    {
    // Create a DataTable with the modified rows.
    DataTable addedCategories =
      CategoriesDataTable.GetChanges(DataRowState.Added);
    
    // Configure the SqlCommand and SqlParameter.
    SqlCommand insertCommand = new SqlCommand(
        "usp_InsertCategories", connection);
    insertCommand.CommandType = CommandType.StoredProcedure;
    SqlParameter tvpParam = insertCommand.Parameters.AddWithValue(
        "@tvpNewCategories", addedCategories);
    tvpParam.SqlDbType = SqlDbType.Structured;
    
    // Execute the command.
    insertCommand.ExecuteNonQuery();
    }
    

提交回复
热议问题