How do I check if an index exists before creating it in a script?

Posted on 2005-04-02
Medium Priority
Last Modified: 2012-08-14
I'm trying to add an index via a script, but want to check if it exists first.

I use this for procedures:
if exists (select * from dbo.sysobjects where id = object_id(N'[dbo].[spCreateScenarioNHrooms]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)

but it doesn't seem as if I can use " IsIndex".

The larger question is how to alter a table completely and save the data. What's the normal practice for adding via a script? I don't what the dba to slit my throat if the script blows up. But I also don't want to re-create the entire table (saving data, re-importing data, whatever) just to add one measley index.

a. how to check if an index exists before creating it?
b. what's the normal practice for creating an index in a script?

Thanks !

Question by:Alaska Cowboy
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 34

Accepted Solution

Brian Crowe earned 200 total points
ID: 13688034
try using the sysindex table

IF EXISTS (SELECT * FROM dbo.sysindexes WHERE id = object_id(N'[dbo].[spCreateScenarioNHrooms]') and OBJECTPROPERTY(id, N'IsProcedure') = 1)

just look up CREATE INDEX in BOL...

   ON authors (zip)

Assisted Solution

Satyabodhi earned 100 total points
ID: 13688283
if not exists (select * from sysindexes where name = 'IX_Your_Table_columnA)
      create unique index IX_Your_Table_columnA
      on Your_Table(ColumnA)


Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

The Delta outage: 650 cancelled flights, more than 1200 delayed flights, thousands of frustrated customers, tens of millions of dollars in damages – plus untold reputational damage to one of the world’s most trusted airlines. All due to a catastroph…
What if you have to shut down the entire Citrix infrastructure for hardware maintenance, software upgrades or "the unknown"? I developed this plan for "the unknown" and hope that it helps you as well. This article explains how to properly shut down …
This video shows how to set up a shell script to accept a positional parameter when called, pass that to a SQL script, accept the output from the statement back and then manipulate it in the Shell.
Via a live example, show how to shrink a transaction log file down to a reasonable size.
Suggested Courses

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question