SQL Query check if unique constraint is Updated , If its not Altered then run Alter Query

Indudhar Gowda 426 Reputation points
2022-06-02T19:25:47.037+00:00

I need a IF Statement to check and run SQL Query

  alter table [ReportableResults] add constraint   
   Unique_ReportableResults_ReportableResultCode_IsCalculated unique (ReportableResultCode, IsCalculated);  

Above Code is Working Fine.....But I dont want to run Everytime...

I want to check if its already altered then not need to run the Above Query.

208012-image.png

SQL Server Integration Services
Developer technologies | Transact-SQL
Developer technologies | Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
SQL Server | Other
{count} votes

Answer accepted by question author
  1. Tom Cooper 8,496 Reputation points
    2022-06-03T03:51:17.907+00:00

    The following code will create the constraint if there is no object named Unique_ReportableResults_ReportableResultCode_IsCalculated, but if it already exists, the code will do nothing.

    If Not Exists(Select * From sys.objects Where Name = 'Unique_ReportableResults_ReportableResultCode_IsCalculated')
      alter table [ReportableResults] add constraint
       Unique_ReportableResults_ReportableResultCode_IsCalculated unique (ReportableResultCode, IsCalculated);
    

    Tom

    2 people found this answer helpful.
    0 comments No comments

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as 'Accepted' by the question author and 'Recommended' by moderators, which helps users know the answer solved the author's problem.