错误"从字符串转换日期和/或时间时转换失败"

时间:2015-09-03 13:03:30

标签: c# sql asp.net ajaxcontroltoolkit

我有一个不合时宜的SQL查询,在获取日期值时失败:

 String strQuery = @"SELECT TOP 100000" +
    "[dbo].[Service].[company_name] AS 'Company Name', [dbo].[Service].[status_description] AS 'Status Description'," +
    "DATEPART(month, [dbo].[Service].[date_entered]) AS 'Month', COUNT([dbo].[Service].[status_description]) AS 'Count'" +
    "FROM [dbo].[Service] WITH(NOLOCK)" +
    "WHERE  ([dbo].[Service].[status_description] = @Status)" +

    // ****  I used the following to get values from Ajax CalendarExtender 
    // **** (Ajax Format from: yyyy-MM-ddTHH:mm:ss.mmm to: yyyy-MM-ddT23:59:59.000) *******
    "AND ([dbo].[Service].[date_entered] BETWEEN '@DateFrom' AND '@DateTo')" +

    "GROUP BY [dbo].[Service].[company_name], [dbo].[Service].[status_description]," +
    "DATEPART(month, [dbo].[Service].[date_entered])" +
    "ORDER BY [dbo].[Service].[status_description] ASC;";

    System.Globalization.CultureInfo en = new System.Globalization.CultureInfo("en-US");
    SqlConnection con = new SqlConnection(strConnString);
    SqlCommand cmd = new SqlCommand(strQuery + "", con);
    cmd.Parameters.AddWithValue("@Status", DdlTickets.SelectedItem.Value);
    cmd.Parameters.AddWithValue("@DateFrom", TxtDateFrom.Text);
    cmd.Parameters.AddWithValue("@DateTo", TxtDateTo.Text);        

    SqlDataAdapter da = new SqlDataAdapter(cmd);
    DataSet ds = new DataSet();
    cmd.Connection = con;
    try
    {
        con.Open();
        if (DdlTickets.Items.Count > 1)
        {
            da.Fill(ds, strQuery);

            // *** the values come from Ajax, but when It gets to fill the Gridview, it fails with error ****

            GridView1.DataSource = ds.Tables[strQuery];
            GridView1.DataBind();
            BtnCSV.Visible = true;
        }
        if (GridView1.Rows.Count <= 0)
        {
            BtnCSV.Visible = false;
        }
        else
        {
            //Set Later
        }
    }
    catch (Exception ex)
    {
        throw ex;
    }
    finally
    {
        con.Close();
        con.Dispose();
    }

我尝试使用以下代码转换CalendarExtender中的默认值,但它不起作用:

cmd.Parameters.AddWithValue("@DateFrom", DateTime.ParseExact(TxtDateFrom.Text, "yyyy-MM-ddTHH:mm:ss.mmm", CultureInfo.InvariantCulture));
cmd.Parameters.AddWithValue("@DateTo", DateTime.ParseExact(TxtDateTo.Text, "yyyy-MM-ddTHH:mm:ss.mmm", CultureInfo.InvariantCulture));

如果我执行以下查询而不是上面的查询,并直接获取值,则可以使用:

"AND ([dbo].[Service].[date_entered] BETWEEN '2015-04-02T00:00:00.000' AND '2015-09-02T23:59:59.000')" +

任何可能导致错误的想法?非常感谢您的帮助!

1 个答案:

答案 0 :(得分:2)

您不需要为参数使用单引号。使用单引号,您的数据库管理员会将其视为string literal而不是参数。

删除它们。如果除了那之外的一切都很好,它就会起作用。

$ awk '/X/ && !s { f = 1 } f { sub(/Y,/, "B,") } 1' file
Y,
A,
X,
C,
D,
B,
A,
X,
B,

还有一些事情;