Link to home
Create AccountLog in
Avatar of JEClark1
JEClark1Flag for United States of America

asked on

Create index via SQL stored procedure

I am attempting to create a stored procedure which will generate indexes on SQL tables, if they do not already exist
Code is below.

However, I keep getting the error:
Msg 1913, Level 16, State 1, Line 1
The operation failed because an index or statistics with name 'IX_d_StudentsCurrentShortCS_studentNumber' already exists on table 'REAdw.dbo.d_StudentsCurrentShortCS'.

I know that I cannot create an index if the index name alreay exists in sys.indexex, but I am using code to check for it and delete if already there, before creating/re-creating.

Any guidance would be most appreciated

- - - - -
USE [REAdw]
GO
/****** Object:  StoredProcedure [dbo].[spd_cube_transcript]    Script Date: 11/16/2010 10:23:43 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
alter proc spd_MakeIndexes
as
IF EXISTS (SELECT name FROM sys.indexes
            WHERE name = N'IX_d_StudentsCurrentShortCS_studentNumber')
    DROP INDEX IX_d_StudentsCurrentShortCS_studentNumber ON REAdw.dbo.d_StudentsCurrentShortCS;
GO
CREATE INDEX IX_d_StudentsCurrentShortCS_studentNumber
    ON REAdw.dbo.d_StudentsCurrentShortCS (studentNumber);
GO
ASKER CERTIFIED SOLUTION
Avatar of EvilPostIt
EvilPostIt
Flag of United Kingdom of Great Britain and Northern Ireland image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
Avatar of JEClark1

ASKER

Thank you for a quick and concise response!  Worked perfectly.
Glad to be of assistance.