0

I have a table named RETAILTRANSACTIONTABLE which has a column named BUSINESSDATE which has date in format(yyyy-mm-dd) 2015-05-22.

I want to comapre this date with batch.StartDateTime of format (dd-mm-yyyy hh:mm:ss) 05-10-2015 12:09:03.

var dateAndTime = batch.StartDateTime;
var date = dateAndTime.ToShortDateString();
string query = "SELECT COUNT(discamount) AS DISCOUNTCOUNT "+
                " FROM ax.RETAILTRANSACTIONTABLE where "+
                "(CONVERT(VARCHAR(10),BUSINESSDATE,105) >= '" + date
                + "') and DISCAMOUNT > 0

Using the above query gives me all the values of the column I just want the count of values greater than or equal to batch date

Gajendra Rajput
  • 93
  • 1
  • 13

3 Answers3

0

You can use :

var dateAndTime = batch.StartDateTime;
var date = dateAndTime.ToShortDateString();
string query = "SELECT COUNT(discamount) AS DISCOUNTCOUNT "+
            " FROM ax.RETAILTRANSACTIONTABLE "+
            " WHERE BUSINESSDATE >= CONVERT(DATE, '" + date + "', 105) 
            and DISCAMOUNT > 0 "

And, bonus, this use index on BUSINESSDATE if an index exist.

or better as @FelixPamittan said, use a prepared statement with binding :

var dateAndTime = batch.StartDateTime;
var date = dateAndTime.ToShortDateString();
string query = "SELECT COUNT(discamount) AS DISCOUNTCOUNT "+
            " FROM ax.RETAILTRANSACTIONTABLE "+
            " WHERE BUSINESSDATE >= :theDate 
            and DISCAMOUNT > 0 "
Khonsort
  • 483
  • 4
  • 6
0

I think this will do the trick for you

var dateAndTime = batch.StartDateTime;
var date = dateAndTime.ToShortDateString();
string query = "SELECT COUNT(discamount) AS DISCOUNTCOUNT " +
                " FROM ax.RETAILTRANSACTIONTABLE WHERE" +
                "BUSINESSDATE > = (CONVERT(VARCHAR, " + @dateParam + " ,105) >= '" + 
                + "') and DISCAMOUNT > 0

SqlConnection connection = new SqlConnection(/* connection info */);
SqlCommand command = new SqlCommand(query, connection);

command.Parameters.AddWithValue("dateParam", date.ToString("yyyy/mm/dd"));
Shweta Pathak
  • 775
  • 1
  • 5
  • 21
0

With the help of above answers I modified it and finally got the solution

var dateAndTime = batch.StartDateTime;
var date = dateAndTime.ToString("yyyy-MM-dd");
string query = "SELECT COUNT(discamount) AS DISCOUNTCOUNT "+
               " FROM ax.RETAILTRANSACTIONTABLE where "+                    
               "BUSINESSDATE >= '" + date + "'" + 
               " and DISCAMOUNT > 0
Gajendra Rajput
  • 93
  • 1
  • 13