CJ7
CJ7

Reputation: 23275

Quickest way to create DataTable from query?

What is the code with the smallest number of lines that will generate a DataTable from this SQL query?

SELECT * 
FROM [Table1] 
WHERE ([Date] BETWEEN @Date1 AND @Date2) AND 
      ([Field1] IS NULL OR [Field2] IS NULL)

Upvotes: 5

Views: 14787

Answers (3)

Habib
Habib

Reputation: 223237

Use SqlDataAdapter to fill a DataTable.

DataTable dt = new DataTable();
using (SqlConnection yourConnection = new SqlConnection("connectionstring"))
{
    using (SqlCommand cmd = new SqlCommand("....your sql statement", yourConnection))
    {
        using (SqlDataAdapter da = new SqlDataAdapter(cmd))
        {
            da.Fill(dt);
        }
    }
}

Use using block with your SqlConnection, SqlCommand and SqlDataAdapter since they implement IDisposable interface. Also use Parameterized query

Upvotes: 16

Ozgur
Ozgur

Reputation: 368

SqlDataAdaptor and FillSchema

It will create your table on the fly

Applied On a DataSet

http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldataadapter.aspx

Applied On a DataTable

http://msdn.microsoft.com/en-us/library/152bda9x.aspx

Upvotes: 1

codingbiz
codingbiz

Reputation: 26386

Try this

SqlCommand command = new SqlCommand(query, conn);
DataTable dt = new DataTable();
using(SqlDataReader reader = command.ExecuteReader())
{
     dt.Load(reader);
}

Upvotes: 3

Related Questions