INFORMATION_SCHEMA查询运行缓慢

时间:2017-05-04 19:17:04

标签: sql sql-server information-schema

请放轻松,因为这是我的第一篇文章。

我无法弄清楚什么会修复我们的INFORMATION_SCHEMA上的以下查询从运行这么慢。据我所知,这些观点很好地被锁定了。这是在SQL Server 2014 Standard上。

最近,我们恢复了使用此查询的数据库。此数据库是生产数据库的测试版本。在该恢复之前,此查询在几秒或更短的时间内运行,但现在返回36行需要3-5分钟。此查询运行速度明显更快,最后一行被注释掉,大约4秒左右,返回60行。

有没有人想知道怎样做才能让它再次变快?

可能会回答更多问题的其他详细信息:查询在生产数据库上也需要很长时间。视图上没有任何索引。

    SELECT pf.TABLE_CATALOG AS PK_TABLE_DATABASE, 
           pf.TABLE_SCHEMA AS PK_SCHEMA_NAME, 
           pf.TABLE_NAME AS PK_TABLE_NAME,
           pf.COLUMN_NAME AS PK_FIELD_NAME, 
           ff.TABLE_CATALOG AS FK_TABLE_DATABASE, 
           ff.TABLE_SCHEMA AS FK_SCHEMA_NAME,
           ff.TABLE_NAME AS FK_TABLE_NAME, 
           ff.COLUMN_NAME AS FK_FIELD_NAME, 
           pf.ORDINAL_POSITION AS ORDINAL
FROM INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE ff
    ON rc.CONSTRAINT_NAME = ff.CONSTRAINT_NAME
    AND rc.CONSTRAINT_SCHEMA = ff.CONSTRAINT_SCHEMA
    AND rc.CONSTRAINT_CATALOG = ff.CONSTRAINT_CATALOG
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE pf 
    ON rc.UNIQUE_CONSTRAINT_NAME = pf.CONSTRAINT_NAME
    AND rc.UNIQUE_CONSTRAINT_SCHEMA = pf.CONSTRAINT_SCHEMA
    AND rc.UNIQUE_CONSTRAINT_CATALOG = pf.CONSTRAINT_CATALOG
    AND ff.ORDINAL_POSITION = pf.ORDINAL_POSITION --line in question 

感谢您的时间。

2 个答案:

答案 0 :(得分:0)

我会按此顺序尝试: 1)更新统计数据 2)重建索引 3)确认机器中的可用内存不受压力。 4)检查某种类型的活动或锁(sp_lock)

答案 1 :(得分:0)

试试这个,

SELECT pf.TABLE_CATALOG AS PK_TABLE_DATABASE, 
           pf.TABLE_SCHEMA AS PK_SCHEMA_NAME, 
           pf.TABLE_NAME AS PK_TABLE_NAME,
           pf.COLUMN_NAME AS PK_FIELD_NAME, 
           ff.TABLE_CATALOG AS FK_TABLE_DATABASE, 
           ff.TABLE_SCHEMA AS FK_SCHEMA_NAME,
           ff.TABLE_NAME AS FK_TABLE_NAME, 
           ff.COLUMN_NAME AS FK_FIELD_NAME, 
           pf.ORDINAL_POSITION AS ORDINAL
FROM  INFORMATION_SCHEMA.KEY_COLUMN_USAGE ff
INNER JOIN INFORMATION_SCHEMA.KEY_COLUMN_USAGE pf 
ON ff.ORDINAL_POSITION = pf.ORDINAL_POSITION --line in question 
where exists
(
select 1 
from INFORMATION_SCHEMA.REFERENTIAL_CONSTRAINTS rc
where rc.CONSTRAINT_NAME = ff.CONSTRAINT_NAME
    AND rc.CONSTRAINT_SCHEMA = ff.CONSTRAINT_SCHEMA
    AND rc.CONSTRAINT_CATALOG = ff.CONSTRAINT_CATALOG
    and rc.UNIQUE_CONSTRAINT_NAME = pf.CONSTRAINT_NAME
    AND rc.UNIQUE_CONSTRAINT_SCHEMA = pf.CONSTRAINT_SCHEMA
    AND rc.UNIQUE_CONSTRAINT_CATALOG = pf.CONSTRAINT_CATALOG
)