Dataset table row count in SQL Server

The DataSet in ADO.NET serves as an in-memory representation of a set of data that we retrieve from a data source, such as a SQL database, through SQL statements. It contains a DataTableCollection, which is a collection of zero or more DataTable objects.

DataTable within the DataSet

Each DataTable within the DataSet represents a table-like structure, with rows and columns, that holds a copy of the data retrieved from the data source. The number of DataTable objects within the DataTableCollection corresponds to the number of distinct data sets or result sets obtained from the SQL statement.

For example, if we execute a SQL query that retrieves data from two different tables, the DataSet will contain two DataTable objects, each representing the data from one of the tables. These DataTable objects will be part of the DataTableCollection within the DataSet.

DataTableCollection

We can access the DataTableCollection using the Tables property of the DataSet. The Tables property allows us to iterate over the collection, access individual DataTable objects, or retrieve information about the number of tables present using the Count property.

Follwoing is an example to demonstrate accessing the DataTableCollection and retrieving the number of tables within a DataSet:

Full Source VB.NET
Imports System.Data.SqlClient Public Class Form1 Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click Dim connetionString As String Dim connection As SqlConnection Dim command As SqlCommand Dim adapter As New SqlDataAdapter Dim ds As New DataSet Dim sql As String connetionString = "Data Source=ServerName;Initial Catalog=DatabaseName;User ID=UserName;Password=Password" sql = "Your SQL Statement Here" connection = New SqlConnection(connetionString) Try connection.Open() command = New SqlCommand(sql, connection) adapter.SelectCommand = command adapter.Fill(ds, "SQL Temp Table") adapter.Dispose() command.Dispose() connection.Close() MsgBox("Number of row(s) - " & ds.Tables(0).Rows.Count) Catch ex As Exception MsgBox("Can not open connection ! ") End Try End Sub End Class

Conclusion

By examining the number of DataTable objects within the DataTableCollection, we can determine the number of distinct result sets or tables present within the DataSet.