执行SqlDataReader时的DateTime转换错误

时间:2016-01-15 15:39:56

标签: c# asp.net sql-server datetime

执行阅读器从表中检索某些日期时,我遇到了问题。

首先,我有一个页面将一些变量转移到另一个页面:

//calStart.SelectedDate is a DateTime value
Response.Redirect("SpecialReports_Results.aspx?userListValues=" + userListValues + "&groupListValues=" + groupListValues + "&calSelected=" + calStart.SelectedDate);

然后,在新页面上:

    //To retrieve the values that were sent over
    string userListValues = Request.QueryString["userListValues"];
    string groupListValues = Request.QueryString["groupListValues"];
    string dateSelected = Request.QueryString["calSelected"];

    // SQL Server connection stuff + string argument
    SqlCommand command2 = new SqlCommand();
    command2.Connection = gconn;

    String sql2 = "SELECT MAX([Day]) as TheDay FROM Days WHERE User_ID = @User_ID AND [Day] < '@dateSelected' AND NOT EXISTS (SELECT 1 FROM Days WHERE User_ID = @User_ID AND [DAY] >= '@dateSelected')";
    command2.CommandText = sql2;

    command2.Parameters.Add(new SqlParameter("@User_ID", ""));
    command2.Parameters.Add(new SqlParameter("@dateSelected", dateSelected));

    List<string> dates = new List<string>();

    //userID is a List<string>
    foreach (string str in userID)
    {
        command2.Parameters["@User_ID"].Value = str;

        using (SqlDataReader reader = command2.ExecuteReader())
        {
            while (reader.Read()) //Getting error here: Conversion failed when converting datetime from character string.
            {
                if (reader.HasRows)
                {
                    dates.Add(reader["Day"].ToString());
                }
            }
        }
    }

Days的设置如下:

User_ID | Day
----------------------------------
10      | 2010-11-09 00:00:00.000
20      | 2015-12-06 00:00:00.000
30      | 2012-01-12 00:00:00.000
40      | 2013-07-23 00:00:00.000

Day列的类型为DateTime

我尝试通过执行以下操作将字符串dateSelectedList<string>日期转换为DateTime

DateTime confirmedDate = DateTime.Parse(dateSelected);
List<DateTime> dates = new List<DateTime>()

但我得到同样的错误。

注意:在Microsoft的SQL Server Management Studio中执行时,SQL语句可以正常工作。

1 个答案:

答案 0 :(得分:2)

我认为您需要删除'@dateSelected'上的单引号。

这样,您的代码就会将其视为string literal,而不是参数。

String sql2 = "SELECT MAX([Day]) as TheDay FROM Days WHERE User_ID = @User_ID AND [Day] < @dateSelected AND NOT EXISTS (SELECT 1 FROM Days WHERE User_ID = @User_ID AND [DAY] >= @dateSelected)";

由于没有从字符串到日期时间的隐式对话,您的读者会尝试将此@dateSelected字符串文字转换为日期时间,但它会失败。