Generation 5 » Dropping Unique Constraints in SQL Server

 Subscribe to our RSS Feed | About Us

Dropping Unique Constraints in SQL Server

Search for:

The problem

Search

I got started with relational databases with mysql,  so I’m in the habit of making
database changes with SQL scripts,  rather than using a GUI.  Microsoft SQL Server
requires that we specify the name of a unique constraint when we want to drop it.  If
you’re thinking ahead,  you can specify a name when you create the constraint;  if
you don’t,  SQL Server will make up an unpredictable name,  so you can’t write a
simple script to drop the constraint.

A Solution
In the spirit of “How To Drop A Primary Key in SQL Server“,  here’s a stored
procedure that queries the data dictionary to find the names of any unique constraint
on a specific table and column and drop them:
CREATE PROCEDURE [dbo].[DropUniqueConstraint]
    @tableName NVarchar(255),
    @columnName NVarchar(255)
AS
    DECLARE @IdxNames CURSOR
   
    SET @IdxNames = CURSOR FOR
        select sysindexes.name from sysindexkeys,syscolumns,sysindexes
            WHERE
                syscolumns.[id] = OBJECT_ID(N'[dbo].['+@tableName+N']')
                AND sysindexkeys.[id] = OBJECT_ID(N'[dbo].['+@tableName+N']')
                AND sysindexes.[id] = OBJECT_ID(N'[dbo].['+@tableName+N']')
                AND syscolumns.name=@columnName
                AND sysindexkeys.colid=syscolumns.colid
                AND sysindexes.[indid]=sysindexkeys.[indid]
                AND (
                    SELECT COUNT(*) FROM sysindexkeys AS si2
                    WHERE si2.id=sysindexes.id
                    AND si2.indid=sysindexes.indid
                )=1
    OPEN @IdxNames
    DECLARE @IdxName Nvarchar(255)
    FETCH NEXT FROM @IdxNames INTO @IdxName   
    WHILE @@FETCH_STATUS = 0 BEGIN
        DECLARE @dropSql Nvarchar(4000)
        SET @dropSql=
            N'ALTER TABLE  ['+@tableName+ N']
                DROP CONSTRAINT ['+@IdxName+ N']'
        EXEC(@dropSql)
           
        FETCH NEXT FROM @IdxNames
        INTO @IdxName
    END
CLOSE @IdxNames
DEALLOCATE @IdxNames

Usage is straightforward:
EXEC [dbo].[DropUniqueConstraint]
    @tableName='TargetTable',
    @columnName='TargetColumn'

This script has a limitation:  it only drops unique constraints that act on a single
column,  not constraints that act on multiple columns.   It is smart enough,  however, 
to not drop multiple-column constraints in case one of them involves @columnName .
Feedback from SQL stored procedure wizards would be mostly certainly welcome.

Paul Houle on June 26th 2008 in SQL

Comments
http://gen5.info/q/2008/06/26/dropping-unique-constraints-in-sql-server/[1/16/2014 3:58:30 PM]

Comments (0)
Login

Archives

June 2012 (1)
August 2010 (1)
May 2010 (1)
June 2009 (2)
April 2009 (1)
March 2009 (1)
February 2009 (3)
January 2009 (3)
November 2008 (1)
August 2008 (2)
July 2008 (5)
June 2008 (5)
May 2008 (2)
April 2008 (6)
March 2008 (8)
June 2006 (1)
February 2006 (1)

Categories

AJAX (2)
Asynchronous Communications (16)
Biology (1)
Books (1)
Design (1)
Distributed (1)
Exceptions (2)
Functional Programming (1)
GIS (1)
Ithaca (1)
Japan (1)
Math (1)
Media (3)
Nature (1)
Semantic Web (3)
Tools (28)
CRUD (1)
Dot Net (17)
Freebase (2)
GWT (9)
Java (7)
Linq (2)
PHP (6)
Server Frameworks (1)
Silverlight (12)
SQL (5)
Uncategorized (1)
Web (2)
Analytics (1)
Generation 5 » Dropping Unique Constraints in SQL Server

There are no comments posted yet. Be the first one!

Post a new comment
Enter text right here!

Comment as a Guest, or login:
Name

Email

Website (optional)

Displayed next to your comments.

Not displayed publicly.

If you have a website, link to it here.

None
Subscribe to None

Submit Comment

Copyright © 2013 Generation 5.
WordPress Theme design.

http://gen5.info/q/2008/06/26/dropping-unique-constraints-in-sql-server/[1/16/2014 3:58:30 PM]

More Related Content

DOCX
บทที่3
PPTX
Introduction to database
PPTX
Introduction to database
ODP
Smidige databaser
PPTX
MySql:Basics
PDF
MySQL for beginners
บทที่3
Introduction to database
Introduction to database
Smidige databaser
MySql:Basics
MySQL for beginners

What's hot (18)

PDF
Datacon LA - MySQL without the SQL - Oh my!
PPTX
Introduction databases and MYSQL
PDF
Longhorn PHP - MySQL Indexes, Histograms, Locking Options, and Other Ways to ...
PPTX
MySql:Introduction
PPTX
Discover the Power of the NoSQL + SQL with MySQL
PDF
Json within a relational database
PDF
Dutch PHP Conference 2021 - MySQL Indexes and Histograms
DOCX
ANDROID USING SQLITE DATABASE ADMINISTRATORS ~HMFTJ
PDF
MySQL 8.0 Operational Changes
PDF
MySQL Replication Update - DEbconf 2020 presentation
PDF
JavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScript
PPTX
Open Source 1010 and Quest InSync presentations March 30th, 2021 on MySQL Ind...
PPT
Jdbc
DOCX
Accessing data with android cursors
PPTX
Beginner guide to mysql command line
PDF
Developers’ mDay 2019. - Bogdan Kecman, Oracle – MySQL 8.0 – why upgrade
Datacon LA - MySQL without the SQL - Oh my!
Introduction databases and MYSQL
Longhorn PHP - MySQL Indexes, Histograms, Locking Options, and Other Ways to ...
MySql:Introduction
Discover the Power of the NoSQL + SQL with MySQL
Json within a relational database
Dutch PHP Conference 2021 - MySQL Indexes and Histograms
ANDROID USING SQLITE DATABASE ADMINISTRATORS ~HMFTJ
MySQL 8.0 Operational Changes
MySQL Replication Update - DEbconf 2020 presentation
JavaScript and Friends August 20th, 20201 -- MySQL Shell and JavaScript
Open Source 1010 and Quest InSync presentations March 30th, 2021 on MySQL Ind...
Jdbc
Accessing data with android cursors
Beginner guide to mysql command line
Developers’ mDay 2019. - Bogdan Kecman, Oracle – MySQL 8.0 – why upgrade
Ad

Similar to Dropping unique constraints in sql server (16)

PDF
Columndrop
DOCX
SQL & PLSQL
PPT
Structure query language - Data definition language.ppt
PPT
PDF
RDBMS Lab03 applying constraints (UIU)
PPT
database management system lessonchapter
ODP
Ms sql-server
PPTX
ms-sql-server-150223140402-conversion-gate02.pptx
PPTX
Sql commands
PPTX
apply Integrity constraints on database table
PPT
SQL Tutorial - Table Constraints
PPT
Intro to tsql unit 8
DOCX
SQL Tutorial for BCA-2
PPTX
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
PPTX
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
PPTX
Data Definition Language Commands in DBMS
Columndrop
SQL & PLSQL
Structure query language - Data definition language.ppt
RDBMS Lab03 applying constraints (UIU)
database management system lessonchapter
Ms sql-server
ms-sql-server-150223140402-conversion-gate02.pptx
Sql commands
apply Integrity constraints on database table
SQL Tutorial - Table Constraints
Intro to tsql unit 8
SQL Tutorial for BCA-2
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
SQL-Tutorial.P1241112567Pczwq.powerpoint.pptx
Data Definition Language Commands in DBMS
Ad

More from Paul Houle (20)

PDF
Chatbots in 2017 -- Ithaca Talk Dec 6
PDF
Estimating the Software Product Value during the Development Process
PPTX
Universal Standards for LEI and other Corporate Reference Data: Enabling risk...
PPTX
Fixing a leaky bucket; Observations on the Global LEI System
PDF
Cisco Fog Strategy For Big and Smart Data
PPTX
Making the semantic web work
PPTX
Ontology2 platform
PPTX
Ontology2 Platform Evolution
PDF
Paul houle the supermen
PDF
Paul houle what ails enterprise search
PDF
Subjective Importance Smackdown
PDF
Extension methods, nulls, namespaces and precedence in c#
PDF
Prefix casting versus as-casting in c#
PDF
Paul houle resume
PDF
Keeping track of state in asynchronous callbacks
PDF
Embrace dynamic PHP
PDF
Once asynchronous, always asynchronous
PDF
What do you do when you’ve caught an exception?
PDF
Extension methods, nulls, namespaces and precedence in c#
PDF
Pro align snap 2
Chatbots in 2017 -- Ithaca Talk Dec 6
Estimating the Software Product Value during the Development Process
Universal Standards for LEI and other Corporate Reference Data: Enabling risk...
Fixing a leaky bucket; Observations on the Global LEI System
Cisco Fog Strategy For Big and Smart Data
Making the semantic web work
Ontology2 platform
Ontology2 Platform Evolution
Paul houle the supermen
Paul houle what ails enterprise search
Subjective Importance Smackdown
Extension methods, nulls, namespaces and precedence in c#
Prefix casting versus as-casting in c#
Paul houle resume
Keeping track of state in asynchronous callbacks
Embrace dynamic PHP
Once asynchronous, always asynchronous
What do you do when you’ve caught an exception?
Extension methods, nulls, namespaces and precedence in c#
Pro align snap 2

Recently uploaded (20)

PPTX
Custom Battery Pack Design Considerations for Performance and Safety
PPTX
agenticai-neweraofintelligence-250529192801-1b5e6870.pptx
PDF
Early detection and classification of bone marrow changes in lumbar vertebrae...
PDF
The-2025-Engineering-Revolution-AI-Quality-and-DevOps-Convergence.pdf
PDF
INTERSPEECH 2025 「Recent Advances and Future Directions in Voice Conversion」
PPTX
AI-driven Assurance Across Your End-to-end Network With ThousandEyes
PDF
Comparative analysis of machine learning models for fake news detection in so...
PPTX
future_of_ai_comprehensive_20250822032121.pptx
PPTX
Training Program for knowledge in solar cell and solar industry
PPTX
Microsoft User Copilot Training Slide Deck
PDF
Transform-Your-Factory-with-AI-Driven-Quality-Engineering.pdf
PDF
NewMind AI Weekly Chronicles – August ’25 Week IV
PDF
The-Future-of-Automotive-Quality-is-Here-AI-Driven-Engineering.pdf
PDF
Accessing-Finance-in-Jordan-MENA 2024 2025.pdf
PPTX
Configure Apache Mutual Authentication
PDF
Convolutional neural network based encoder-decoder for efficient real-time ob...
PDF
Advancing precision in air quality forecasting through machine learning integ...
PPTX
GROUP4NURSINGINFORMATICSREPORT-2 PRESENTATION
PPTX
SGT Report The Beast Plan and Cyberphysical Systems of Control
PDF
Auditboard EB SOX Playbook 2023 edition.
Custom Battery Pack Design Considerations for Performance and Safety
agenticai-neweraofintelligence-250529192801-1b5e6870.pptx
Early detection and classification of bone marrow changes in lumbar vertebrae...
The-2025-Engineering-Revolution-AI-Quality-and-DevOps-Convergence.pdf
INTERSPEECH 2025 「Recent Advances and Future Directions in Voice Conversion」
AI-driven Assurance Across Your End-to-end Network With ThousandEyes
Comparative analysis of machine learning models for fake news detection in so...
future_of_ai_comprehensive_20250822032121.pptx
Training Program for knowledge in solar cell and solar industry
Microsoft User Copilot Training Slide Deck
Transform-Your-Factory-with-AI-Driven-Quality-Engineering.pdf
NewMind AI Weekly Chronicles – August ’25 Week IV
The-Future-of-Automotive-Quality-is-Here-AI-Driven-Engineering.pdf
Accessing-Finance-in-Jordan-MENA 2024 2025.pdf
Configure Apache Mutual Authentication
Convolutional neural network based encoder-decoder for efficient real-time ob...
Advancing precision in air quality forecasting through machine learning integ...
GROUP4NURSINGINFORMATICSREPORT-2 PRESENTATION
SGT Report The Beast Plan and Cyberphysical Systems of Control
Auditboard EB SOX Playbook 2023 edition.

Dropping unique constraints in sql server

  • 1. Generation 5 » Dropping Unique Constraints in SQL Server  Subscribe to our RSS Feed | About Us Dropping Unique Constraints in SQL Server Search for: The problem Search I got started with relational databases with mysql,  so I’m in the habit of making database changes with SQL scripts,  rather than using a GUI.  Microsoft SQL Server requires that we specify the name of a unique constraint when we want to drop it.  If you’re thinking ahead,  you can specify a name when you create the constraint;  if you don’t,  SQL Server will make up an unpredictable name,  so you can’t write a simple script to drop the constraint. A Solution In the spirit of “How To Drop A Primary Key in SQL Server“,  here’s a stored procedure that queries the data dictionary to find the names of any unique constraint on a specific table and column and drop them: CREATE PROCEDURE [dbo].[DropUniqueConstraint]     @tableName NVarchar(255),     @columnName NVarchar(255) AS     DECLARE @IdxNames CURSOR         SET @IdxNames = CURSOR FOR         select sysindexes.name from sysindexkeys,syscolumns,sysindexes             WHERE                 syscolumns.[id] = OBJECT_ID(N'[dbo].['+@tableName+N']')                 AND sysindexkeys.[id] = OBJECT_ID(N'[dbo].['+@tableName+N']')                 AND sysindexes.[id] = OBJECT_ID(N'[dbo].['+@tableName+N']')                 AND syscolumns.name=@columnName                 AND sysindexkeys.colid=syscolumns.colid                 AND sysindexes.[indid]=sysindexkeys.[indid]                 AND (                     SELECT COUNT(*) FROM sysindexkeys AS si2                     WHERE si2.id=sysindexes.id                     AND si2.indid=sysindexes.indid                 )=1     OPEN @IdxNames     DECLARE @IdxName Nvarchar(255)     FETCH NEXT FROM @IdxNames INTO @IdxName        WHILE @@FETCH_STATUS = 0 BEGIN         DECLARE @dropSql Nvarchar(4000)         SET @dropSql=             N'ALTER TABLE  ['+@tableName+ N']                 DROP CONSTRAINT ['+@IdxName+ N']'         EXEC(@dropSql)                     FETCH NEXT FROM @IdxNames         INTO @IdxName     END CLOSE @IdxNames DEALLOCATE @IdxNames Usage is straightforward: EXEC [dbo].[DropUniqueConstraint]     @tableName='TargetTable',     @columnName='TargetColumn' This script has a limitation:  it only drops unique constraints that act on a single column,  not constraints that act on multiple columns.   It is smart enough,  however,  to not drop multiple-column constraints in case one of them involves @columnName . Feedback from SQL stored procedure wizards would be mostly certainly welcome. Paul Houle on June 26th 2008 in SQL Comments http://gen5.info/q/2008/06/26/dropping-unique-constraints-in-sql-server/[1/16/2014 3:58:30 PM] Comments (0) Login Archives June 2012 (1) August 2010 (1) May 2010 (1) June 2009 (2) April 2009 (1) March 2009 (1) February 2009 (3) January 2009 (3) November 2008 (1) August 2008 (2) July 2008 (5) June 2008 (5) May 2008 (2) April 2008 (6) March 2008 (8) June 2006 (1) February 2006 (1) Categories AJAX (2) Asynchronous Communications (16) Biology (1) Books (1) Design (1) Distributed (1) Exceptions (2) Functional Programming (1) GIS (1) Ithaca (1) Japan (1) Math (1) Media (3) Nature (1) Semantic Web (3) Tools (28) CRUD (1) Dot Net (17) Freebase (2) GWT (9) Java (7) Linq (2) PHP (6) Server Frameworks (1) Silverlight (12) SQL (5) Uncategorized (1) Web (2) Analytics (1)
  • 2. Generation 5 » Dropping Unique Constraints in SQL Server There are no comments posted yet. Be the first one! Post a new comment Enter text right here! Comment as a Guest, or login: Name Email Website (optional) Displayed next to your comments. Not displayed publicly. If you have a website, link to it here. None Subscribe to None Submit Comment Copyright © 2013 Generation 5. WordPress Theme design. http://gen5.info/q/2008/06/26/dropping-unique-constraints-in-sql-server/[1/16/2014 3:58:30 PM]