我收到此错误消息:将varchar值'monthDate'转换为数据类型int时转换失败。
我有这个SQL语句:
String[][] results = lm.SqlSelect("SELECT COUNT(*) FROM members_ WHERE DATEPART(month, DateUnsub_) = 'monthDate' AND DATEPART(year, DateUnsub_) = 2011 AND DATEDIFF(day, DateJoined_, DateUnsub_) <= 30");
我在这里有一个int,其值根据dateLookup值而变化:
switch (dateLookup)
{
case "January":
monthDate = 01;
break;
case "February":
monthDate = 02;
break;
case "March":
monthDate = 03;
break;
case "April":
monthDate = 04;
break;
case "May":
monthDate = 05;
break;
case "June":
monthDate = 06;
break;
case "July":
monthDate = 07;
break;
case "August":
monthDate = 08;
break;
case "September":
monthDate = 09;
break;
case "October":
monthDate = 10;
break;
case "November":
monthDate = 11;
break;
case "December":
monthDate = 12;
break;
}
我的问题是 - varchar来自哪里?例如,当我从SQL语句中取出“monthDate”变量并将其替换为数字05时,一切正常。
答案 0 :(得分:2)
'monthDate'
不是变量。
我认为应该是
String[][] results = lm.SqlSelect("SELECT COUNT(*) FROM members_ WHERE DATEPART(month, DateUnsub_) = " +monthDate + " AND DATEPART(year, DateUnsub_) = 2011 AND DATEDIFF(day, DateJoined_, DateUnsub_) <= 30");
考虑使用string.Format()
使其更具可读性或更好,参数化命令可以防止SQL注入攻击。
答案 1 :(得分:0)
您的查询只选择行数。当我查看你的t-sql代码时,你没有选择其他任何东西。
看到您的属性后,请使用以下代码;
switch (dateLookup)
{
case "January":
monthDate = "01";
break;
case "February":
monthDate = "02";
break;
case "March":
monthDate = "03";
break;
case "April":
monthDate = "04";
break;
case "May":
monthDate = "05";
break;
等等。用英语,在数字前后加上引号。