title: Using If Not Exists on Primary Key
body: <p>I have an existing table in my sql server and I want to add a primary key clustered on a column of that table. I know the syntax would be :</p>
  
  <pre><code>ALTER TABLE PromotionBenefit  
  ADD CONSTRAINT PK_PromotionBenefit2 PRIMARY KEY CLUSTERED (PromotionBenefitCode);  
  GO  
  </code></pre>
  
  <p>The problem is that column already has a primary key (same constraint name) on it. So it throws an error. That is fine. I would like to know if it's possible to add an IF NOT Exists on my query so it wouldn't throw any error. </p>
  
  <p>What would be the syntax to use?</p>
  
  <p>EDIT: Is there a way of using this way: IF NOT EXISTS.... CREATE PRIMARY KEY CLUSTERED instead of altering table like shown above?
  Can it be done like this way :</p>
  
  <pre><code>IF NOT EXISTS (SELECT * FROM sys.indexes WHERE object_id = OBJECT_ID(N'[dbo].[PromotionBenefit]') AND name = N'idx_EventCode')
  CREATE NONCLUSTERED INDEX [idx_EventCode] ON [dbo].[PromotionBenefit]
  (
      [EventCode] 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, FILLFACTOR = 80) ON [PRIMARY]
  GO
  </code></pre>