传递要执行的查询结果

时间:2017-01-09 16:36:28

标签: sql sql-server tsql indexing

我想将以下查询的结果传递给自己的查询:

SELECT
  'CREATE INDEX [missing_index_' 
  + CONVERT (VARCHAR, mig.index_group_handle) + '_' 
  + CONVERT (VARCHAR, mid.index_handle) + '_' 
  + LEFT (PARSENAME (mid.statement, 1),32) + ']' 
  + ' ON ' + mid.statement + ' (' + ISNULL(mid.equality_columns, '') 
  + 
  CASE
    WHEN mid.equality_columns IS NOT NULL AND mid.inequality_columns IS NOT NULL 
    THEN ','
    ELSE ''
  END
  + ISNULL(mid.inequality_columns, '') + ')' 
  + ISNULL(' INCLUDE (' + mid.included_columns + ')', '') AS create_index_statement
FROM sys.dm_db_missing_index_groups mig
INNER JOIN sys.dm_db_missing_index_group_stats migs ON migs.group_handle = mig.index_group_handle
INNER JOIN sys.dm_db_missing_index_details mid ON mig.index_handle = mid.index_handle
WHERE
  migs.avg_total_user_cost * (migs.avg_user_impact / 100.0) 
    * (migs.user_seeks + migs.user_scans) > 10

1 个答案:

答案 0 :(得分:1)

您可以将所有行连接成一个字符串,即使用sp_executesql的执行

-- BUILD STATEMENT
DECLARE
    @SQL NVARCHAR (MAX) = (
        SELECT
            'CREATE INDEX [missing_index_' + CONVERT (
                VARCHAR(MAX)(,
                mig.index_group_handle
            ) + '_' + CONVERT (VARCHAR, mid.index_handle) + '_' + LEFT (
                PARSENAME (mid.statement, 1),
                32
            ) + ']' + ' ON ' + mid.statement + ' (' + ISNULL(mid.equality_columns, '') + CASE
        WHEN mid.equality_columns IS NOT NULL
        AND mid.inequality_columns IS NOT NULL THEN
            ','
        ELSE
            ''
        END + ISNULL(mid.inequality_columns, '') + ')' + ISNULL(
            ' INCLUDE (' + mid.included_columns + ')',
            ''
        ) + ';' AS create_index_statement
        FROM
            sys.dm_db_missing_index_groups mig
        INNER JOIN sys.dm_db_missing_index_group_stats migs ON migs.group_handle = mig.index_group_handle
        INNER JOIN sys.dm_db_missing_index_details mid ON mig.index_handle = mid.index_handle
        WHERE
            migs.avg_total_user_cost * (migs.avg_user_impact / 100.0) * (
                migs.user_seeks + migs.user_scans
            ) > 10 FOR XML PATH (''),
            TYPE ).
        VALUE
            ('.', 'NVARCHAR(MAX)');

-- EXECUTE STATEMENT
EXECUTE sp_executesql @SQL;

HOWEVER 我强烈建议不要以这种方式创建索引,在创建索引时还有太多其他因素要考虑,这不考虑读/写比率,或许多类似的可以合并为一个的建议等。索引既是一门艺术,也是一门科学,所以我不认为有一个神奇的修复查询可以为你做到这一点。