How to: Script Out Unique Constraint creation script

I have a list of Unique Constraints which creation scripts I would need.

Is there an easy way to do this? (something like querying sp_help, sys.objects,..)
Or would I need to do this manually for every constraint ( on 30+ tables)?

  • Generating several similar SSIS packages (file data source to DB)
  • Using a database API cursor with JDBC and SQLServer to select batch results
  • Java/MSSQL: java.sql.SQLException Invalid object name 'TableName'
  • SQL Server Passthrough query as basis for a DAO recordset in Access
  • Query a website in SSIS
  • SQL Server execution plan XML into table
  • Workaround I am using at the moment:
    in SSMS

    • Object Explorer
      • Database
      • Table
      • Constraints
        • ‘script constraint as’
        • ‘CREATE to’

    2 Solutions collect form web for “How to: Script Out Unique Constraint creation script”

    You can try something like this:

        ColumnName =,
        TableName =,   
        CreateCmd = 'ALTER TABLE ' + OBJECT_SCHEMA_NAME(t.object_id) + '.' + + ' ADD CONSTRAINT ' + + ' UNIQUE(' + + ')'
         sys.indexes i
         sys.index_columns ic ON i.index_id = ic.index_id AND i.object_id = ic.object_id
         sys.columns c ON ic.column_id = c.column_id AND ic.object_id = c.object_id
         sys.tables t ON c.object_id = t.object_id
         is_unique_constraint = 1

    This gives you a listing of columns and tables where a unique constraint is applied to, and it gives you the T-SQL command to newly create that UNIQUE CONSTRAINT

    Ever used Powershell?

    $null = [Reflection.Assembly]::LoadWithPartialName("Microsoft.SqlServer.Smo");
    $svr = New-Object Microsoft.SqlServer.Management.Smo.Server("YourServerInstance");

    Databases, Tables and Indexes are collections you can iterate over.

    MS SQL Server is a Microsoft SQL Database product, include sql server standard, sql server management studio, sql server express and so on.