07-31-2023, 03:51 AM
In some situations, it could be desirable to ensure the Unique key does not exists before create it. In such cases, the script below might help:
IF Exists(SELECT * FROM sys.indexes WHERE name Like '<index_name>')
ALTER TABLE dbo.<target_table_name> DROP CONSTRAINT <index_name>
GO
ALTER TABLE dbo.<target_table_name> ADD CONSTRAINT <index_name> UNIQUE NONCLUSTERED (<col_1>, <col_2>, ..., <col_n>)
GO
IF Exists(SELECT * FROM sys.indexes WHERE name Like '<index_name>')
ALTER TABLE dbo.<target_table_name> DROP CONSTRAINT <index_name>
GO
ALTER TABLE dbo.<target_table_name> ADD CONSTRAINT <index_name> UNIQUE NONCLUSTERED (<col_1>, <col_2>, ..., <col_n>)
GO