0

当我在我的 SQL 数据库(来自管理工作室)上运行以下脚本时,我得到了我期望的结果 -

SELECT * 
FROM [Case] 
WHERE ABS((DATEDIFF(DAY, [DateAccident], '2013-01-01'))) < 100;

当我增加/减少值 100 时,我得到更多/更少的匹配,完全符合预期。

但是,当我尝试从我的 WinForms 应用程序(在 C# 中)产生相同的结果时,我得到的结果比我应该得到的要多得多 -

public static DataTable DOACases(DateTime doa, int days)
{
    try
    {
        DataTable table = new DataTable();
        string sqlText = "SELECT * " +
                         "FROM [Case] " +
                         "WHERE ABS((DATEDIFF(DAY, [DateAccident], " + doa.ToString().Substring(0,10) + "))) < " + days.ToString() + ";";
        SqlCommand sqlCom = new SqlCommand(sqlText);
        table = Express.GetTable(sqlCom);
        return table;
    }
    catch (Exception eX)
    {
        throw new Exception("Case: DOACases(Date)" + Environment.NewLine + eX.Message);
    }
}

我不知道为什么

PS。Express.GetTable(sqlCom) 只是在数据库上创建一个连接以及使用 DataReader 填充 DataTable 的必要代码,并且已经工作了数百次,所以我怀疑问题是否存在。

4

2 回答 2

1

Thanks to allo-man, using parameters worked.

The final code looked as follows -

public static DataTable DOACases(DateTime doa, int days)
    {
        try
        {
            DataTable table = new DataTable();
            string sqlText = "SELECT * " +
                             "FROM [Case] " +
                             "WHERE ABS((DATEDIFF(DAY, [DateAccident], @Date))) < @Days;";
            SqlCommand sqlCom = new SqlCommand(sqlText);
            sqlCom.Parameters.Add("@Date", SqlDbType.Date).Value = doa;
            sqlCom.Parameters.Add("@Days", SqlDbType.Int).Value = days;
            table = Express.GetTable(sqlCom);
            return table;
        }
        catch (Exception eX)
        {
            throw new Exception("Case: DOACases(Date)" + Environment.NewLine + eX.Message);
        }
    }
于 2013-10-19T11:35:23.690 回答
0

You better use parameters but here the problem is

'" + doa.ToString("yyyy-MM-dd" , CultureInfo.InvariantCulture) + "'

you need single quotes

于 2013-10-18T13:54:55.090 回答