Introduction

SQL Server Stored Procedures support System.Data.DataTable as a parameter. We can pass the DataTable to the Stored Procedure using ADO.Net in the same way as we provided using the System.Data.SqlParameter class, but needs a few changes in the datatype.
Normally we provide DbType of SqlParameter for a normal parameter like varchar, nvarchar, int and so on as in the following code.
  1. SqlParameter sqlParam= new SqlParameter();
  2. sqlParam.ParameterName = "@StudentName";
  3. sqlParam.DbType = DbType.String;
  4. sqlParam.Value = StudentName;
But in the case of a Table parameter, we do not need to provide a DbType as the parameter data type. We need to provide SqlType rather then DbType.
Example
  1. SqlParameter Parameter = new SqlParameter;
  2. Parameter.ParameterName = "@PhoneBook";
  3. Parameter.SqlDbType = SqlDbType.Structured;
  4. Parameter.Value = PhoneTable;
The following example receives a list of phone books and stores them in a database using ADO.Net. The example retrieves the phone book details from the list and stores them into the DataTable and passes this table to the Stored Procedure named NewPhoneBook as a parameter.
  1. //Phone book list
  2. List<PhoneBook> PhoneBooks
  3. //CReating Table
  4. DataTable PhoneTable = new DataTable();
  5. // Adding Columns
  6. DataColumn COLUMN=new DataColumn();
  7. COLUMN.ColumnName="ID";
  8. COLUMN.DataType= typeof(int);
  9. PhoneTable.Columns.Add(COLUMN);
  10. COLUMN = new DataColumn();
  11. COLUMN.ColumnName = "ContactNumber";
  12. COLUMN.DataType = typeof(string);
  13. PhoneTable.Columns.Add(COLUMN);
  14. COLUMN = new DataColumn();
  15. COLUMN.ColumnName = "ContactName";
  16. COLUMN.DataType = typeof(string);
  17. PhoneTable.Columns.Add(COLUMN);
  18. // INSERTING DATA
  19. foreach (UserPhoneBook UPB in PhoneBooks)
  20. {
  21. DataRow DR = PhoneTable.NewRow();
  22. DR[0] = UPB.UserName;
  23. DR[1] = UPB.ContactNumber;
  24. DR[2] = UPB.ContactName;
  25. PhoneTable.Rows.Add(DR);
  26. }
  27. //Parameter declaration
  28. SqlParameter[] Parameter = new SqlParameter[2];
  29. Parameter[0].ParameterName = "@PhoneBook";
  30. Parameter[0].SqlDbType = SqlDbType.Structured;
  31. Parameter[0].Value = PhoneTable;
  32. Parameter[1].ParameterName = "@Return_Value";
  33. Parameter[1].Direction = ParameterDirection.ReturnValue;
  34. //Executing Procedure
  35. SqlHelper.ExecuteNonQuery(this.ConnectionString, CommandType.StoredProcedure, "[NewPhoneBook]", Parameter);
Summary

I hope you have learned how to pass a table to a Stored Procedure as a parameter using ADO.Net in C#.