结论:
1、导致慢的主要原因是:索引 !此处where条件时间没有加索引。如果唯一则添加唯一索引,若不唯一则添加组合唯一索引。
1、EF 查询 比ADO稍微慢一点点,原因不详。
2、在原生ADO.Net中 使用 参数化查询 比 使用非参数化sql拼接 慢几十倍!!原因不详。
ADO.Net代码测试
public List<v_yjdateggjgModel> SelectList(int yjxzqid, int ncpid, DateTime start, DateTime end) { List<v_yjdateggjgModel> list = new List<v_yjdateggjgModel>();
//第一条sql,采用参数化查询 用时36秒 查询1100条数据 // string sql = "select yjxzqid,ncpid,rq,sjttjg,sjpfjg,sjlsjg,ycttjg,ycpfjg,yclsjg from v_yjdateggjg where yjxzqid=@yjxzqid and ncpid=@ncpid and (rq>=@start and rq<=@end)";
//第二条 sql,采用 sql拼接 用时1.5秒 查询 1100数据 string sql = "select yjxzqid,ncpid,rq,sjttjg,sjpfjg,sjlsjg,ycttjg,ycpfjg,yclsjg from v_yjdateggjg where yjxzqid = "+ yjxzqid + " and ncpid = "+ ncpid + " and (rq >= '"+start.ToString("yyyy-MM-dd")+ "' and rq <= '" + end.ToString("yyyy-MM-dd") + "')"; //SqlParameter[] sqlparms = new SqlParameter[] //{ // new SqlParameter("@ncpid",ncpid) , // new SqlParameter("@yjxzqid",yjxzqid), // new SqlParameter("@start",start), // new SqlParameter("@end",end), //}; using (SqlDataReader reader = SqlHelper.ExecuteReader(sql)) { if (reader.HasRows) { while (reader.Read()) { v_yjdateggjgModel info = new v_yjdateggjgModel(); info.yjxzqid = (int)SqlHelper.FromDbNull(reader["yjxzqid"]); info.ncpid = (int)SqlHelper.FromDbNull(reader["ncpid"]); info.rq = (DateTime)SqlHelper.FromDbNull(reader["rq"]); info.sjttjg = (decimal?)SqlHelper.FromDbNull(reader["sjttjg"]); info.sjpfjg = (decimal?)SqlHelper.FromDbNull(reader["sjpfjg"]); info.sjlsjg = (decimal?)SqlHelper.FromDbNull(reader["sjlsjg"]); info.ycttjg = (decimal?)SqlHelper.FromDbNull(reader["ycttjg"]); info.ycpfjg = (decimal?)SqlHelper.FromDbNull(reader["ycpfjg"]); info.yclsjg = (decimal?)SqlHelper.FromDbNull(reader["yclsjg"]); list.Add(info); } } } return list; }
EF代码
// EF 查询方式一 // var data1 = db.v_yjdateggjg.Where(d => d.yjxzqid == yjxzqid && d.ncpid == ncpid && (d.rq >= start && d.rq <= end)).ToList(); // EF 查询方式二 // string sql = "select * from v_yjdateggjg where yjxzqid=@yjxzqid and ncpid=@ncpid and (rq>=@start and rq<=@end)"; // var sqlparms = new SqlParameter[] { // new SqlParameter("@ncpid",ncpid), // new SqlParameter("@yjxzqid",yjxzqid), // new SqlParameter("@start",start), // new SqlParameter("@end",end), //}; // var data1 = db.Database.SqlQuery<v_yjdateggjg>(sql, sqlparms).ToList();
数据库内部测试
//sql 参数化查询 1100条数据 3秒
declare @yjxzqid int =9; declare @ncpid int= 35; declare @start datetime = '2014-5-1'; declare @end datetime='2017-5-1'; select yjxzqid,ncpid,rq,sjttjg,sjpfjg,sjlsjg,ycttjg,ycpfjg,yclsjg from v_yjdateggjg where yjxzqid=@yjxzqid and ncpid=@ncpid and (rq>=@start and rq<=@end) // sql拼接 1100条 1秒 select yjxzqid,ncpid,rq,sjttjg,sjpfjg,sjlsjg,ycttjg,ycpfjg,yclsjg from v_yjdateggjg where yjxzqid=9 and ncpid=35 and (rq>'2014-5-1' and rq<'2017-5-1')
v_