长时间执行请求

时间:2013-09-22 08:23:00

标签: c# sql sql-server linq sql-server-2008

美好的一天!

List<TotalServiseCalls> TSC = (
    from scall in contextOMNIDB.UserFields698.AsEnumerable()
    where scall.f2_creationd >= referenceDate
    group scall by scall.f2_creationd.Month into scalls
    select new TotalServiseCalls
    {
        mountN = (from sc in contextOMNIDB.UserFields698.AsEnumerable()
            where sc.f2_creationd.Month == scalls.Key
            select sc.f2_creationd).FirstOrDefault(),
        date = (from sc in contextOMNIDB.UserFields698.AsEnumerable()
            where sc.f2_creationd.Month == scalls.Key
            select sc.f2_creationd.ToString("MMMM yyyy")).FirstOrDefault(),
        totalCount = scalls.Count()
     }).OrderBy(p => p.mountN).ToList();
MSSQL服务器有很多应用程序,其负载非常高。 此查询执行40秒。这是因为服务器拥塞或查询的复杂性?

这些表有大约一万条记录,大小只有一兆字节。

2 个答案:

答案 0 :(得分:1)

很难说您提供的信息是查询还是拥堵。你可以改进两件事:

  1. contextOMNIDB.UserFields698.AsEnumerable()放入变量
  2. 将其添加到可重复使用的表单中:from sc in contextOMNIDB.UserFields698.AsEnumerable() where sc.f2_creationd.Month == scalls.Key select sc.f2_creationd
  3. 这是一个可能的重构版本:

    var userFields = contextOMNIDB.UserFields698.AsEnumerable();
    List<TotalServiseCalls> TSC = (
        from scall in userFields
        where scall.f2_creationd >= referenceDate
        group scall by scall.f2_creationd.Month into scalls
        select new TotalServiseCalls
        {
          mountN = Helper(userFields, scalls.Key).FirstOrDefault(),
          date = Helper(userFields, scalls.Key).Select(o => o.ToString("MMMM yyyy")).FirstOrDefault(),
          totalCount = scalls.Count()
        }).OrderBy(p => p.mountN).ToList();
    

    使用帮助方法(我必须使用object因为我对业务对象不够):

    private IEnumerable<object> Helper(IEnumerable<object> userFields, object key)
    {
      return from sc in userFields
             where sc.f2_creationd.Month == key
             select sc.f2_creationd;
    }
    

答案 1 :(得分:1)

您不必查询contextOMNIDB.UserFields698.AsEnumerable() 3次,您可以从群组中获取第一条记录,您可以将月份作为分组的关键:

List<TotalServiseCalls> TSC = (
    from scall in contextOMNIDB.UserFields698.AsEnumerable()
    where scall.f2_creationd >= referenceDate
    group scall by scall.f2_creationd.Month into scalls
    select new {
        mountN = scalls.Key,
        date = scalls.Select(x => x.ToString("MMMM yyyy").First(),
        // You can use scalls.OrderBy(x => x (or any other order)).First()
        // if you want to get specific date
        totalCount = scalls.Count()
    }
).OrderBy(p => p.mountN).ToList();

这是一个简单的例子:

var list = new List<Tuple<string, string>>();
list.Add(new Tuple<string, string>("test1", "2"));
list.Add(new Tuple<string, string>("test1", "1"));
list.Add(new Tuple<string, string>("test2", "1"));
list.Add(new Tuple<string, string>("test2", "6"));
list.GroupBy(x => x.Item1)
    .Select(x => 
            new {
                a = x.Key,
                b = x.OrderByDescending(y => y).First(),
                c = x.Count()
            }
    ).ToList()