【问题标题】:How to find index exists on multiple columns如何查找多个列上存在的索引
【发布时间】:2018-10-24 05:40:08
【问题描述】:

我有 delta 脚本 SQL 查询,我必须检查是否存在特定索引,如果不存在则创建一个。

例如 表结构:

表A Col1 整数 Col2 varchar Col3 varchar Col4 日期时间

查询是:

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 上是否创建了索引,如果没有则创建。

我该怎么做?

【问题讨论】:

    标签: sql sql-server database indexing


    【解决方案1】:

    试试这个查询,它将返回索引的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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2022-11-22
      • 2016-11-29
      • 1970-01-01
      • 2013-08-06
      • 2015-01-26
      • 2016-09-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多