Reputation: 33
I'm trying to return a query (in a gridview in ASP.NET) WHERE Time >= DateTime.Now.Add(-60). The WHERE
clause has been giving me no end of difficulties.
DateTime pastTime = DateTime.Now.Add(-60);
ds_DB.SelectCommand = "SELECT * FROM [vPurchaseTotals] WHERE [TimeOfTransaction] >= " + pastTime;
My issue is getting pastTime to convert properly, so it only returns the newer data. [TimeOfTransaction]
is a time(7)
data type in the table.
How do I parse C#'s DateTime
to SQL Server's Time
?
Upvotes: 0
Views: 478
Reputation: 545
Here, try this:
using(SqlConnection conn = new SqlConnection(yourConnectionString))
{
DateTime pastTime = DateTime.Now.Add(-60);
ds_DB.SelectCommand = @"SELECT * FROM [vPurchaseTotals]
WHERE [TimeOfTransaction] >= @PastTime";
SqlCommand cm = conn.CreateCommand();
cm.CommandText = ds_DB.SelectCommand;
cm.Parameters.Add("@PastTime", SqlDbType.Time).Value = pastTime.TimeOfDay; //For comparison with TSQL TIME type
try
{
conn.Open();
// Do what you need to do here.
}
catch(SqlException e)
{
// Handle Exception
}
finally
{
conn.Close();
}
}
Just for future reference, you should always parameterize your queries. It ends up being a lot safer and cleaner/easier to read and adjust.
EDIT: Are you using a SqlDataAdapter
class? Is that what ds_DB is an instance of? I would personally just use a string value for your query and then implement the SqlDataAdapter
like this:
try
{
conn.Open();
using(SqlDataAdapter da = new SqlDataAdapter(cm))
{
da.Fill(DataTable dt);
}
}
Upvotes: 1