Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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)
like image 514
CJ7 Avatar asked Oct 18 '12 05:10

CJ7


3 Answers

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

like image 153
Habib Avatar answered Nov 16 '22 21:11

Habib


Try this

SqlCommand command = new SqlCommand(query, conn);
DataTable dt = new DataTable();
using(SqlDataReader reader = command.ExecuteReader())
{
     dt.Load(reader);
}
like image 27
codingbiz Avatar answered Nov 16 '22 23:11

codingbiz


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

like image 1
Ozgur Avatar answered Nov 16 '22 21:11

Ozgur