C# SQL Server compare date with string

后端 未结 2 1248
悲哀的现实
悲哀的现实 2021-01-15 17:36

I have to compare a table field that is a date stored as varchar in the format \'dd/MM/yyyy\' with a date value, but the comparison fails. I have exception

2条回答
  •  感动是毒
    2021-01-15 18:29

    First, you should not store dates as strings.
    As Panagiotis Kanavos wrote in his comment - this is a serious bug. You can't sort by such a column, you can't search for date ranges, and most important - you can't control if someone enters an invalid value - nothing is stopping someone from entering "Alfredo" to that column.
    For more information, read Aaron Bertrand's Bad habits to kick : choosing the wrong data type.

    Second, you should not pass dates from .Net to Sql server as strings. you should pass instances of DateTime as parameters. The .Net DateTime maps directly to SQL Server's Date.

    If you can't change the data type of the column, you can at least convert it to date using the proper convert style (103 in your case).

    Here is a better way to do it:

    var sql = "select * from TB_RICHIESTE where CONVERT(DATE, [Date], 103) <= @Date";
    

    Then you add the @Date parameter to the SqlCommand:

    com.Parameters.Add("@Date", SqlDbType.Date).Value = date.Date;
    

提交回复
热议问题