0

当我尝试运行我的程序时出现错误:

将 varchar 数据类型转换为 datetime 数据类型导致值超出范围。

我的 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 数据库表

在此处输入图像描述

在此处输入图像描述

4

1 回答 1

0

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

  • select, 作为返回Date
  • Where, 因为你在比较 aDate和 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);
于 2012-07-28T04:08:30.153 回答