简体   繁体   中英

Converting C# DateTime to T-SQL Time in SelectCommand

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 ?

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);
     }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM