concept DataTable in category sql

This is an excerpt from Manning's book SQL Server MVP Deep Dives.
ADO.NET and SQL Server collaborate to perform the conversions necessary to create a new TABLE type that is usable by T-SQL. The DataTable object is probably the easiest to use and familiar to most .NET database application developers. The DbDataReader object is part of ADO.NET’s alternative factory-method-based objects. SqlDataRecord is used within SQL CLR code, which is the .NET code that executes within the SQL Server process.
The sample client is an ASP.NET website application contained in the Client directory in this chapter’s sample files. The Simple.aspx page shows two methods of using TVPs from ADO.NET with the DataTable and DbDataReader objects. The first of two buttons on the form uses the dkSelectFromTVP stored procedure created earlier in the chapter to return the list of rows in the TVP passed to it. Listing 1 shows the two methods. The BuildDataTable method creates a new DataTable and populates it with data, this time with some cities and villages in the Alaska Interior. The real meat of the code is in the DataTableButton Click event procedure.
Listing 1. Code to use a DataTable to pass a TVP to a stored procedure
private DataTable BuildDataTable() { DataTable dt = new DataTable("AlaskaCities"); dt.Columns.Add("ID", typeof(System.Int32)); dt.Columns.Add("String", typeof(System.String)); dt.Rows.Add(1, "Ester"); dt.Rows.Add(2, "Chena"); dt.Rows.Add(3, "North Pole"); dt.Rows.Add(4, "Chatanika"); dt.Rows.Add(5, "Fox"); return dt; } protected void DataTableButton_Click(object sender, EventArgs e) { DataTable dt = BuildDataTable(); using (SqlConnection cnn = new SqlConnection(ConfigurationManager .ConnectionStrings["TVPs"].ConnectionString)) { SqlCommand cmd = new SqlCommand("dkSelectFromTVP", cnn); cmd.CommandType = CommandType.StoredProcedure; cmd.Parameters.AddWithValue("@TVParam", dt); cnn.Open(); SqlDataReader dr = cmd.ExecuteReader(); GridView1.DataSource = dr; GridView1.DataBind(); } }The event procedure starts by creating the DataTable object to be passed to the stored procedure. The rest of the code is fairly typical ADO.NET code that creates a command object, adds the DataTable as a parameter, and calls the ExecuteReader method to return the resultset, which is bound to a GridView control on the web form. Figure 3 shows the results.
The notable thing about this example is that there isn’t anything notable about it, compared to how you’ve been writing ADO.NET code for years. And because the structure of the DataTable is such a close match for the TABLE type defined earlier, the code doesn’t even have to specify the SqlDbType of the table-valued parameter. Usually specifying the type is not optional, so you should get into the habit of always providing that information. You’ll see how in the next example.