/*
Server:		sun791aps.sunstore.ch
Format:		GCM 
Business:	TPPHAR
type:		PROD
Version:	21.3.11111.00064

02.11.2022, TSC
*/
USE [Arizona];

BEGIN TRANSACTION;
SET XACT_ABORT ON;
SET NOCOUNT ON;

DECLARE @index_to_drop TABLE ([columns_in_index] VARCHAR(MAX) NOT NULL,
                              [index_name] VARCHAR(500) NULL);

INSERT @index_to_drop ([columns_in_index])
VALUES ('ET_APS_TS'),
       ('ET_entry_address'),
       ('ET_entry_type'),
       ('ET_master_ID'),
       ('ET_predefined_entry'),
       ('ET_sales_tax_code'),
       ('ET_bmc_user_profile'),
       ('ET_currency');

/* find index name with defined columns */
WITH [ColInfo]
  AS (SELECT      [o].[name] AS [TblName],
                  [s].[name] + '.' + [o].[name] AS [SchemaTbl],
                  [i].[name] AS [IndexName],
                  [i].[is_primary_key] AS [IsPrimaryKey],
                  [i].[is_unique_constraint] AS [IsUniqueConstraint],
                  [i].[is_unique] AS [IsUnique],
                  [c].[name] AS [ColName],
                  [c].[is_computed] AS [IsComputedCol],
                  [ic].[is_included_column] AS [IsIncludedCol],
                  [ic].[key_ordinal],
                  [i].[filter_definition] AS [FilterDefinition],
                  CHAR(13) + CHAR(10) AS [crlf],
                  ';' + CHAR(13) + CHAR(10) + 'GO' + CHAR(13) + CHAR(10) AS [crlfgo]
        FROM      [sys].[objects] [o]
       INNER JOIN [sys].[schemas] [s]
          ON [o].[schema_id] = [s].[schema_id]
       INNER JOIN [sys].[columns] [c]
          ON [o].[object_id] = [c].[object_id]
       INNER JOIN [sys].[indexes] [i]
          ON [c].[object_id] = [i].[object_id]
       INNER JOIN [sys].[index_columns] [ic]
          ON [i].[index_id]  = [ic].[index_id]
         AND [o].[object_id] = [ic].[object_id]
         AND [c].[column_id] = [ic].[column_id]
       WHERE      [o].[name] = 'entry'
--AND i.filter_definition IS NOT NULL
)

--SELECT itd.columns_in_index
--      ,itd.index_name
--	  ,lst.IndexName
--	  ,lst.IndexColumns
--	  ,lst.IncludedColumns
UPDATE      [itd]
   SET      [itd].[index_name] = [lst].[IndexName]
  FROM      (   SELECT       DISTINCT [x].[TblName],
                                      [x].[IndexName],
                                      [x].[IsPrimaryKey],
                                      [x].[IsUniqueConstraint],
                                      [x].[IsUnique],
                                      --,size.IndexSizeKB
                                      [c].[IndexColumns],
                                      [ci].[IncludedColumns],
                                      [cc].[ComputedColumns],
                                      [x].[FilterDefinition],
                                      [x].[crlf] + '-- ' + [x].[IndexName] + [x].[crlf] +
                                      --check drop
                                      'IF INDEXPROPERTY(OBJECT_ID(''' + [x].[SchemaTbl] + '''), ''' + [x].[IndexName]
                                      + ''' , ''IndexID'' ) IS NOT NULL BEGIN;' + [x].[crlf]
                                      + CASE
                                             WHEN [x].[IsPrimaryKey] = 1 THEN NULL
                                             WHEN [x].[IsUniqueConstraint] = 1 THEN
                                                 --drop statement
                                                 '	ALTER TABLE ' + [x].[SchemaTbl] + ' DROP CONSTRAINT ' + [x].[IndexName] + ';'
                                                 + [x].[crlf] + 'END' + [x].[crlfgo]
                                                 --check create
                                                 + 'IF INDEXPROPERTY(OBJECT_ID(''' + [x].[SchemaTbl] + '''), ''' + [x].[IndexName]
                                                 + ''' , ''IndexID'' ) IS NULL BEGIN;' + [x].[crlf] +
                                      --create statement
                                      +'	ALTER TABLE '
                                                 + [x].[SchemaTbl] + ' ADD CONSTRAINT ' + [x].[IndexName] + ' UNIQUE ('
                                                 + [c].[IndexColumns] + ');' + [x].[crlf] + 'END' + [x].[crlfgo]
                                             ELSE
                                                 --drop statement
                                                 '	DROP INDEX ' + [x].[SchemaTbl] + '.' + [x].[IndexName] + ';' + [x].[crlf]
                                                 + 'END' + [x].[crlfgo]
                                                 --check create
                                                 + 'IF INDEXPROPERTY(OBJECT_ID(''' + [x].[SchemaTbl] + '''), ''' + [x].[IndexName]
                                                 + ''' , ''IndexID'' ) IS NULL BEGIN;' + [x].[crlf] +
                                      --create statement
                                      +'	CREATE '
                                                 + CASE
                                                        WHEN [x].[IsUnique] = 1 THEN 'UNIQUE '
                                                        ELSE '' END + 'INDEX ' + [x].[IndexName] + ' ON ' + [x].[SchemaTbl] + '('
                                                 + [c].[IndexColumns] + ')'
                                                 + ISNULL(' INCLUDE(' + [ci].[IncludedColumns] + ')', '')
                                                 + ISNULL(' WHERE ' + [x].[FilterDefinition], '') + ';' + [x].[crlf] + 'END'
                                                 + [x].[crlfgo] END AS [DropCreateSQL]
                  FROM       [ColInfo] [x]
                 CROSS APPLY (   SELECT STUFF([sq].[strXML], 1, 2, '') AS [IndexColumns]
                                   FROM (   SELECT ', ' + ISNULL([x2].[ColName], '')
                                              FROM [ColInfo] [x2]
                                             WHERE [x].[TblName]        = [x2].[TblName]
                                               AND [x].[IndexName]      = [x2].[IndexName]
                                               AND [x2].[IsIncludedCol] = 0
                                             ORDER BY [x2].[key_ordinal]
                                            FOR XML PATH('')) [sq]([strXML]) ) [c]
                 OUTER APPLY (   SELECT STUFF([sq].[strXML], 1, 2, '') AS [IncludedColumns]
                                   FROM (   SELECT ', ' + ISNULL([x2].[ColName], '')
                                              FROM [ColInfo] [x2]
                                             WHERE [x].[TblName]        = [x2].[TblName]
                                               AND [x].[IndexName]      = [x2].[IndexName]
                                               AND [x2].[IsIncludedCol] = 1
                                             ORDER BY [x2].[key_ordinal]
                                            FOR XML PATH('')) [sq]([strXML]) ) [ci]
                 OUTER APPLY (   SELECT STUFF([sq].[strXML], 1, 2, '') AS [ComputedColumns]
                                   FROM (   SELECT ', ' + ISNULL([x2].[ColName], '')
                                              FROM [ColInfo] [x2]
                                             WHERE [x].[TblName]        = [x2].[TblName]
                                               AND [x].[IndexName]      = [x2].[IndexName]
                                               AND [x2].[IsComputedCol] = 1
                                             ORDER BY [x2].[key_ordinal]
                                            FOR XML PATH('')) [sq]([strXML]) ) [cc] ) [lst]
 INNER JOIN @index_to_drop [itd]
    ON [lst].[IndexColumns] = [itd].[columns_in_index];

SELECT * 
FROM @index_to_drop [itd];

/* declare variables */
DECLARE @index_name VARCHAR(MAX);

DECLARE [drop_index] CURSOR LOCAL FAST_FORWARD READ_ONLY FOR
SELECT [itd].[index_name]
  FROM @index_to_drop [itd]
 WHERE [itd].[index_name] IS NOT NULL;

OPEN [drop_index];

FETCH NEXT FROM [drop_index]
 INTO @index_name;

WHILE @@FETCH_STATUS = 0
BEGIN
    EXEC ('DROP INDEX ' + @index_name + ' ON dbo.entry;');

    FETCH NEXT FROM [drop_index]
     INTO @index_name;
END;

CLOSE [drop_index];
DEALLOCATE [drop_index];


ROLLBACK TRANSACTION;
