如何查找多列上存在的索引

时间:2018-10-24 05:40:09

标签: sql sql-server database indexing

我有增量脚本SQL查询,在其中我必须检查是否存在特定索引,如果没有,则创建一个。

例如 表结构:

tableA
Col1 int
Col2 varchar
Col3 varchar
Col4 DateTime

查询为:

IF EXISTS (SELECT 1  
            FROM sys.indexes AS i  
            INNER JOIN sys.index_columns AS ic   
            ON i.object_id = ic.object_id 
                     AND i.index_id = ic.index_id  
                     WHERE i.object_id =OBJECT_ID('dbo.tableA') 
                     AND COL_NAME(ic.object_id,ic.column_id) = 'Col2' ) 
BEGIN
    PRINT 'Index Exists!'
END
ELSE
BEGIN
              PRINT 'Nonclustered does not Exists!'
              IF NOT EXISTS (SELECT name FROM sys.indexes WHERE name = N'IX_tableA_Col2_Col3') 
              BEGIN
              PRINT 'Creating index on tableA'
              CREATE NONCLUSTERED INDEX [IX_tableA_Col2_Col3] ON [dbo].[tableA]
              (
                  [Col2] ASC,
                  [Col3] ASC
              )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, SORT_IN_TEMPDB = OFF, DROP_EXISTING = OFF, ONLINE = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
              END
END

该查询能够检查Col2上是否有索引,但是我要实现的是检查是否在Col2Col3上创建了索引然后创建。

我该怎么做?

1 个答案:

答案 0 :(得分:2)

尝试此查询,它将返回在两个指定列上创建的索引的index_id

declare @tblName varchar(20) = 'yourTable',
        @col1 varchar(20) = 'col1',
        @col2 varchar(20) = 'col2';

select index_id from (
    select index_id,
           (select name 
            from sys.columns 
            where object_id = ic.object_id and column_id = ic.column_id
              and name in (@col1, @col2)) name
    from sys.index_columns ic
    where object_name(object_id) = @tblName
) a group by index_id
having count(*) = 2