枚举器的 SQL Select 优化

发布于 2024-09-29 09:19:34 字数 910 浏览 12 评论 0原文

如何针对枚举器优化此查询:

SELECT * FROM Customers

Table Customers
customerId int - has index on it
customerName, etc

返回一组客户的 SqlReader 将以枚举器方式按需读取。虽然它可以返回可以在 foreach 循环中缓慢读取/消耗的巨大数据集,但同一个表上的每个其他查询都会遇到很多争用。如何优化/避免这种情况?游标或选择临时表?

这是一个会引起很多争论的代码示例(我对其进行了分析,数字看起来确实很糟糕):

public void DumpCustomers()
{
    Thread thread = new Thread(AccessCustomers);
    thread.Start();

    // GetCustomers returns enumerator with yield return; big # of customers 
    foreach (Customer customer in GetCustomers())  
    {
       Console.WriteLine(customer.CustomerName);
       System.Threading.Thread.Sleep(200);
    }
    thread.Abort();
}

public void AccessCustomers()
{
   while (true)
   {
      Console.WriteLine(GetCustomer("Zoidberg").CustomerName);
      Thread.Sleep(100);
   }
}


PS 我还需要在 MySQL 中对此进行优化。

How can this query be optimized for enumerators:

SELECT * FROM Customers

Table Customers
customerId int - has index on it
customerName, etc

SqlReader that returns a set customers will be read on-demand in an enumerator fashion. While it can return huge datasets that can be read/consumed slowly in a foreach loop, every other query on the same table will encounter a lot of contentions. How can this be optimized/avoided? Cursors or selecting into temp tables?

Here is a code example that will cause a lot of contentions (I profiled it and the numbers look bad indeed):

public void DumpCustomers()
{
    Thread thread = new Thread(AccessCustomers);
    thread.Start();

    // GetCustomers returns enumerator with yield return; big # of customers 
    foreach (Customer customer in GetCustomers())  
    {
       Console.WriteLine(customer.CustomerName);
       System.Threading.Thread.Sleep(200);
    }
    thread.Abort();
}

public void AccessCustomers()
{
   while (true)
   {
      Console.WriteLine(GetCustomer("Zoidberg").CustomerName);
      Thread.Sleep(100);
   }
}

P.S. I will also need to optimize this in MySQL.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

为人所爱 2024-10-06 09:19:34

1)您是否需要“*”不能指定列。

2) 使用多部分名称 dbo.tablename.fieldname - 这会加快速度

3) 尝试使用 (nolock) 或 (readpast) 进行锁定提示

4) IO 配置文件是什么? SQL每次运行时都必须从磁盘中提取数据吗?

5) 您是否发现服务器上的一个核心已达到最大状态,而另一个核心则处于空闲状态?

6)缓存它!直到您知道发生了更改 - 然后重新加载它。

我已经没有想法了..

1) Do you need the '*' cant you specify the columns.

2) Use multi-part names dbo.tablename.fieldname - this speeds it up

3) try a locking hint with (nolock) or (readpast)

4) Whats the IO profile? Does SQL have to pull the data from disk every time it runs?

5) Do you find one of the cores on your server max out while the other one is idle?

6) Cache it! Until you know there has been a change- then reload it.

I've run out of ideas..

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文