SqlCommand - ExecuteDataTable
Executes the query, and returns the first result set as DataTable.
public static void Main() { DataTable result; const string sql = @" SELECT 1 AS A UNION SELECT 2 UNION SELECT 3 "; using (var conn = new SqlConnection(FiddleHelper.GetConnectionStringSqlServer())) { using (SqlCommand command = conn.CreateCommand()) { conn.Open(); command.CommandText = sql; //C# Extension Method: SqlCommand - ExecuteDataTable result = command.ExecuteDataTable(); // return DataSet (3 tables). conn.Close(); Console.WriteLine(result.Rows.Count); } } }
View Source
using System.Data; using System.Data.SqlClient; public static partial class Extensions { /// <summary> /// Executes the query, and returns the first result set as DataTable. /// </summary> /// <param name="this">The @this to act on.</param> /// <returns>A DataTable that is equivalent to the first result set.</returns> public static DataTable ExecuteDataTable(this SqlCommand @this) { var dt = new DataTable(); using (var dataAdapter = new SqlDataAdapter(@this)) { dataAdapter.Fill(dt); } return dt; } }