【问题标题】:Sql select is slow on table while it has been inserted插入时,表上的 Sql 选择很慢
【发布时间】:2013-04-08 05:06:45
【问题描述】:

我有一个后台作业(C# 控制台应用程序),它在 product_titleParts 表中连续插入数据。只需此作业从 products 表中选择前 100 个产品,将 title 拆分为 part 并插入 product_titleParts 表中。

此表有一个名为“TitlePart”的索引列

另一方面,当我尝试从此表中进行选择时,SQL 查询需要很长时间。 如果我在一段时间后停止控制台应用程序,查询需要 0 秒。一旦我再次启动控制台应用程序,再次选择查询无响应。

在插入另一个作业时从表中选择会导致任何缓慢? 我在 select 上使用 nolock 但没有帮助。

有什么想法吗?

我在控制台应用程序上的代码:

if not exists(select 1 from product_titleParts where productid = @productid
and UserId = @userid and titlePart = @titlePart)
begin
insert into product_titleParts (userid, productid, titlePart)
VALUES (@userid, @productid, @titlePart)
end

我的选择代码:

select productid from product_titleParts 
inner join products
on products.productid = product_titleParts.productid
where titlePart = @titlePart

【问题讨论】:

  • 在您开始在查询中抛出 nolock 提示之前,最好确保您知道后果。他们可能比你想象的更糟糕:blogs.msdn.com/b/davidlean/archive/2009/04/06/…
  • 向我们展示代码。 SQL 和 C#
  • 您可能需要为titlePart 列添加索引。
  • 在我的问题中我已经提到“这个表有一个名为“TitlePart”的索引列
  • 还有很多可能性。你能告诉我们这两个的 SQL 查询计划吗?

标签: sql select indexing


【解决方案1】:

另一方面,我在插入“海量数据”时遇到了类似的问题 (DB/2)

我的解决方案是什么:

插入物很贵,所以我把它们绑在一个块上,比如:

 insert into ...
 values ((a,b,c),(x,y,z), ... )

只锁定表一次,例如。 100 个插入和索引只重建一次

还有一点:当您插入(更新)许多行时,请尝试以独占模式锁定表(取决于 DBMS)。您可以防止所谓的“锁升级”

在 DB2 中你会使用

   lock table xyz in exclusive mode
   update/insert many rows
   unlock table xyz

【讨论】:

    猜你喜欢
    • 2013-09-17
    • 1970-01-01
    • 2023-03-12
    • 2014-09-18
    • 1970-01-01
    • 2012-06-09
    • 1970-01-01
    • 2017-01-07
    • 2013-08-03
    相关资源
    最近更新 更多