Sososo Sososo - 8 days ago 6
C# Question

Datetime Parse Query

I'm trying to catch data between two dates in database.

When I try to execute this query in SQL Server Management Studio, it's working fine.

SELECT
cha_tarihi
FROM
CARI_HESAP_HAREKETLERI
WHERE
ha_tarihi BETWEEN '2016-02-10' AND '2016-10-10';


But when I want to try in my C# project, it's not working, not returning any data from database.

I'm trying about two hours please help what is the problem?

Query in my C# project

var editeddate = DateTime.ParseExact(
dateEdit1.EditValue.ToString(),
"d.M.yyyy hh:mm:ss", CultureInfo.InvariantCulture
);

var editeddate2 = DateTime.ParseExact(
dateEdit2.EditValue.ToString(),
"d.M.yyyy hh:mm:ss", CultureInfo.InvariantCulture
);

query.Sql =
@"select cha_tarihi from CARI_HESAP_HAREKETLERI where cha_tarihi between '" +
editeddate.ToString( "yyyy-MM-dd" ) +
"' AND '" +
editeddate2.ToString("yyyy-MM-dd") +
"'";

Answer
var sql = @"SELECT cha_tarihi 
            FROM   CARI_HESAP_HAREKETLERI 
            WHERE  cha_tarihi BETWEEN $startdate AND $enddate";

var command = new SqlCommand(sql, {your connection});

// You have EditValue.ToString() - what is the type of this value?
// You maybe be able to skip the DateTime.Parse
command.Parameters.Add("@startdate", SqlDbType.DateTime2)
                  .Value = DateTime.Parse(dateEdit1.EditValue)
                                   .ToString("yyyy-MM-dd"); 
command.Parameters.Add("@enddate", SqlDbType.DateTime2)
                  .Value = DateTime.Parse(dateEdit2.EditValue)
                                   .ToString("yyyy-MM-dd");
Comments