Check the existence of Dice?

Asked

Viewed 3,965 times

0

Is there any way to use a Script check if an index already exists in a table?

I got the following script that generates an index in a table:

CREATE NONCLUSTERED INDEX [meu_indice] ON [dbo].[MinhaTabela]
(
[Id] ASC,
[Chave_Id] 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)
GO

Only that as I already created the index in the table, if I try to run the script gives error saying that the index has already been created.

Would have some way to check if the index already exists and only create if it does not exist?

3 answers

1

You can use a IF thus:

If IndexProperty(Object_Id('MyTable'), 'MyIndex', 'IndexId') Is Null

If there is an Indice will return the ID case will not return Null.

Source: Soen

  • You could put the complete script using the code I passed?

  • Even if I have more than one index as in the code I sent? Type Id1 and Id2? Something else, could you put it both ways? I think it would be nice in the answer to have both forms!

1


What I usually do is a select in sys.objects

if (not exists (select null from sys.objects where name = 'meu_indice'))

the complete script gets

if (not exists (select null from sys.objects where name = 'meu_indice'))
    CREATE NONCLUSTERED INDEX [meu_indice] ON [dbo].[MinhaTabela]
    (
    [Id] ASC,
    [Chave_Id] 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)
    GO

0

Use a query in the sysindexes table to verify the existence.

Follow an example:

IF NOT EXISTS(SELECT id FROM sys.sysindexes where name = 'Nome_de_seu_indice')
BEGIN
   EXEC(
   '
    /****** coloque o seu indice aqui dentro do texto
     CREATE UNIQUE NONCLUSTERED INDEX ...
    ...
    ...
')
END;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.