这几天在写业务根据部门号和日期查询数据时,报如下错误: System.Data.SqlClient.SqlException:“从字符串转换日期和/或时间时,转换失败
/// <summary>
/// 根据部门号和日期查询数据
/// </summary>
/// <param name="dept_code">部门号</param>
/// <param name="date">日期(传空则为今天)</param>
/// <returns></returns>
[HttpGet]
public DataTable testTime(string dept_code, string date) {
//connStr里的内容省略了
string connStr = "Server=;Initial Catalog=;User ID=;Password=";
SqlConnection con = new SqlConnection(connStr);
con.Open();
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
StringBuilder sqlStr = new StringBuilder();
sqlStr.Append("select * from table where createTime between " +
" '@date 00:00:00' and '@date 23:59:59' and deptCode = @dept_code");
if(String.IsNullOrEmpty(date))
{
date = DateTime.Now.Date.ToString("yyyy-MM-dd");
}
cmd.Parameters.Add(new SqlParameter("@dept_code", SqlDbType.NVarChar));
cmd.Parameters["@dept_code"].Value = dept_code;
cmd.Parameters.Add(new SqlParameter("@date", SqlDbType.NVarChar));
cmd.Parameters["@date"].Value = date;
cmd.CommandText = sqlStr.ToString();
SqlDataAdapter adapter = new SqlDataAdapter(cmd);
DataTable dataTable = new DataTable();
adapter.Fill(dataTable);
con.Close();
return dataTable;
}
发现是我的sql语句对 @date参数 的拼接有问题,应该把其拼接成 ' ' 的形式,修改成:
//原本错误的
sqlStr.Append("select * from table where createTime between " +
" '@date 00:00:00' and '@date 23:59:59' and deptCode = @dept_code");
//正确的
sqlStr.Append("select * from re_gembaWalkStatistics where createTime between " +
" @date + ' 00:00:00' and @date + ' 23:59:59' and deptCode = @dept_code");