sql 将系统数据组合在一起以生成可用于索引ALTER语句的索引详细信息的脚本。

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了sql 将系统数据组合在一起以生成可用于索引ALTER语句的索引详细信息的脚本。相关的知识,希望对你有一定的参考价值。

WITH    TableColumnCTE
          AS ( SELECT   sch.name SchemaName
                      , tbl.name TableName
                      , col.name ColumnName
                      , ix.name IndexName
               FROM     sys.indexes ix
                        JOIN sys.objects tbl ON tbl.object_id = ix.object_id
                        JOIN sys.index_columns ix_col ON ix_col.object_id = ix.object_id
                                                         AND ix_col.index_id = ix.index_id
                        JOIN sys.columns col ON col.object_id = tbl.object_id
                                                AND col.column_id = ix_col.column_id
                        JOIN sys.schemas sch ON sch.schema_id = tbl.schema_id
               WHERE    tbl.type = 'U'
                        AND ix.type_desc = 'CLUSTERED'
             ) ,
        TableIndexCTE
          AS ( SELECT   ix.SchemaName
                      , ix.TableName
                      , ix.IndexName
                      , STUFF(( SELECT  ', [' + ColumnName + ']'
                                FROM    TableColumnCTE b
                                WHERE   b.SchemaName = ix.SchemaName
                                        AND b.TableName = ix.TableName
                              FOR
                                XML PATH('')
                              ), 1, 2, '') AS ColumnList
               FROM     TableColumnCTE ix
               GROUP BY ix.SchemaName
                      , ix.TableName
                      , ix.IndexName
             )
    SELECT  100 SortOrder
          , cte.TableName
          , 'ALTER TABLE ' + QUOTENAME(cte.SchemaName) + '.' + QUOTENAME(cte.TableName) + ' ALTER COLUMN ' + QUOTENAME(cte.ColumnName)
            + ' NOT NULL' SqlStatement
    FROM    TableColumnCTE cte
    UNION
    SELECT  125 SortOrder
          , cte.TableName
          , 'TRUNCATE TABLE ' + QUOTENAME(cte.SchemaName) + '.' + QUOTENAME(cte.TableName)
    FROM    TableIndexCTE cte
    UNION
    SELECT  150 SortOrder
          , cte.TableName
          , 'DROP INDEX [' + cte.IndexName + '] ON ' + QUOTENAME(cte.SchemaName) + '.' + QUOTENAME(cte.TableName)
    FROM    TableIndexCTE cte
    UNION
    SELECT  200 SortOrder
          , cte.TableName
          , 'CREATE UNIQUE CLUSTERED INDEX [UX_' + cte.SchemaName + '_' + cte.TableName + '] ON ' + QUOTENAME(cte.SchemaName) + '.'
            + QUOTENAME(cte.TableName) + ' (' + cte.ColumnList + ')'
    FROM    TableIndexCTE cte
    ORDER BY 2
          , 1;

以上是关于sql 将系统数据组合在一起以生成可用于索引ALTER语句的索引详细信息的脚本。的主要内容,如果未能解决你的问题,请参考以下文章

组合索引

Mysql知识汇总之常用索引及sql优化

简易发号SQL,可用于生成指定前缀自增序列,如订单号,生成优惠券码等

SQL Server 索引(index) 和 视图(view) 的简单介绍和操作

是否可以将多个 SQL 语句组合在一起?

以最佳方式将矩形组合在一起