将varchar数据类型转换为日期时间数据类型会导致超出范围的值

时间:2012-07-28 02:32:02

标签: c# asp.net visual-studio

我尝试运行程序时出错:

  

将varchar数据类型转换为日期时间数据类型   导致了超出范围的价值。

我的select语句有什么问题吗?

  int month=0;

    if (RadioButtonList1.SelectedIndex == 0)
    { month = 1; }
    else if(RadioButtonList1.SelectedIndex == 1)
    { month = 2; }
    else if(RadioButtonList1.SelectedIndex == 2)
    { month = 3; }

    SqlCommand cmd = new SqlCommand("SELECT thDate, thType, thAmountIn, thAmountOut from [Transaction] Where thDate > dateadd(month, -" + month + ", GETDATE())", myConnection);
    da = new SqlDataAdapter(cmd);
    myConnection.Open();
    da.Fill(ds, "[Transaction]");
    myConnection.Close();
    if (!IsPostBack)
    {
        ViewState["vs_Transaction"] = (DataTable)ds.Tables["Transaction"];
        GridView1.DataSource = ds.Tables["Transaction"];
        GridView1.DataBind();

以下是thDate的数据库表

enter image description here

enter image description here

1 个答案:

答案 0 :(得分:0)

问题在于,您要将数据存储为Varchar,并填充datatable,这可能会期望Datetime。您应该cast query中两个地方的值:

  • select中,以Date
  • 的身份返回
  • Where中,因为您将Date与a进行比较 Varchar

因此,您的select子句将是

SqlCommand cmd = new SqlCommand("SELECT Convert(datetime, thDate,103) as thDate, thType, thAmountIn, thAmountOut from [Transaction] Where Convert(datetime, thDate,103)> dateadd(month, -" + month + ", GETDATE())", myConnection);