C# 将varchar数据类型转换为datetime数据类型导致值超出范围
我尝试运行程序时出错: 将varchar数据类型转换为datetime数据类型 导致值超出范围 我的select语句有什么问题吗C# 将varchar数据类型转换为datetime数据类型导致值超出范围,c#,asp.net,visual-studio,C#,Asp.net,Visual Studio,我尝试运行程序时出错: 将varchar数据类型转换为datetime数据类型 导致值超出范围 我的select语句有什么问题吗 int month=0; if (RadioButtonList1.SelectedIndex == 0) { month = 1; } else if(RadioButtonList1.SelectedIndex == 1) { month = 2; } else if(RadioButtonList1.Selected
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数据库表
问题在于,您将数据存储为
Varchar
,并填充数据表
,这可能需要日期时间
。您应该在两个位置对查询中的值进行cast
:
- 在
中选择
,作为日期返回
- 在
中,其中
,因为您正在将日期
与
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);
是在标题中,我猜有一条评论说“什么是错误?”。。但是我想那已经被删除了:PDo你知道我的编码有什么问题导致了erorr吗?你从哪里得到的错误?什么线路?给我们多一点信息还有,你的数据是varchar类型?这就是它看起来的样子,不再有错误了。但是,没有根据单选按钮选择gridview中的日期。你知道为什么吗?比如说?数据库中的日期是什么,GridView上显示的日期是什么?我已经编辑了顶部。db和gridview中的日期应为sameWell,您确定第一次显示的db结果正常吗?我的意思是,Where子句将0、1或2添加到getdate()(即实际日期),并返回大于该值的字段。您的第一个输出有一个不正确的值,“9/2/2012 10:23..”可能是因为它将字段作为Varchar(又名字符串)而不是日期进行比较。我的意思是,select正在返回其他结果。如果您确定第一个结果是您想要的,请删除where中的“Convert”(如前所述),我已经更改了日期,不再是“9/2/2012 10:23”。您的第一个结果是指2012年9月2日?或因为我删除了where子句中的“Convert”。但它表示在“,”附近预期条件的上下文中指定的非布尔类型的表达式。