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)
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
Try this
SqlCommand command = new SqlCommand(query, conn);
DataTable dt = new DataTable();
using(SqlDataReader reader = command.ExecuteReader())
{
dt.Load(reader);
}
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With