Skip to content
This repository has been archived by the owner on Dec 1, 2018. It is now read-only.

GetData

Aleksey Nemiro edited this page Apr 5, 2014 · 4 revisions

DataSet is useful if you want to get from one query multiple tables of data.

Typically, the data is returned from the stored procedure.

The smaller queries to a database, then better the performance (provided that the query will be optimized).

Getting data as DataSet to reduce the number of database queries.

C#

using (SqlClient client = new SqlClient())
{
  // sql query or stored procedure name
  client.CommandText = "MyStoredProcedure"; 
  // parameters (if necessary)
  client.Parameters.Add("@par1", SqlDbType.Int).Value = 123;
  client.Parameters.Add("@par2", SqlDbType.NVarChar, 50).Value = "hello, world!";
  // query execution
  var data = client.GetData();
  if(data.Tables.Count > 0)
  {
    // has results
    Console.WriteLine("Tables count: {0}", data.Tables.Count);
    // each tables
    foreach(DataTable t in data.Tables)
    {
      // each the table row
      foreach(DataRow r in t.Rows)
      {
        Console.WriteLine("{0}, {1}, {2}", r[0], r[1], r[2]);
      }
    }
  }
  else
  {
    // no results
    Console.WriteLine("Data not found...");
  }
}

Visual Basic .NET

Using client As New SqlClient()
  ' sql query or stored procedure name
  client.CommandText = "MyStoredProcedure"
  ' parameters (if necessary)
  client.Parameters.Add("@par1", SqlDbType.Int).Value = 123
  client.Parameters.Add("@par2", SqlDbType.NVarChar, 50).Value = "hello, world!"
  ' query execution
  Dim data As DataSet = client.GetData()
  If data.Tables.Count > 0 Then
    ' has results
    Console.WriteLine("Tables count: {0}", data.Tables.Count)
    ' each tables
    For Each t As DataTable In data.Tables
      ' each the table row
      For Each r As DataRow In t.Rows
        Console.WriteLine("{0}, {1}, {2}", r(0), r(1), r(2))
      Next
    Next
  Else
    ' no results
    Console.WriteLine("Data not found...")
  End If
End Using