SlideShare une entreprise Scribd logo
1  sur  2
Télécharger pour lire hors ligne
Generation 5 » How to Drop A Primary Key in Microsoft SQL Server

 Subscribe to our RSS Feed | About Us

How to Drop A Primary Key in Microsoft SQL Server

Search for:

One of my pet peeves with Microsoft’s SQL Server is that it requires you to know the
name of constraints and indexes that you’re dropping. This isn’t a problem when
you’re working with the management studio, because it looks at the database
metadata and generates code like
ALTER TABLE [dbo].[someTable] DROP CONSTRAINT
[PK__someTabl__3214EC07271AA44F]

It’s less convenient, however, when you’re writing a set of migration scripts in SQL to
implement changes that you make over the database in time. Specifically, if you
create the table twice in two different databases, the hexadecimal string in the name
of the key will be different — the ALTER TABLE statement will fail when you try to
drop the index later, since the name of the key won’t match.
Here’s a stored procedure that looks up the name of the primary key in the system
catalog and uses dynamic SQL to drop the index:
CREATE PROCEDURE [dbo].[DropPrimaryKey]
@tableName Varchar(255)
AS
/*
Drop the primary key on @TableName
http://gen5.info/q/
Version 1.1
June 9, 2008
*/

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

DECLARE @pkName Varchar(255)
SET @pkName= (
SELECT [name] FROM sysobjects
WHERE [xtype] = 'PK'
AND [parent_obj] = OBJECT_ID(N'[dbo].['+@tableName+N']')
)
DECLARE @dropSql varchar(4000)
SET @dropSql=
'ALTER TABLE [dbo].['+@tableName+']
DROP CONSTRAINT ['+@PkName+']'
EXEC(@dropSql)
GO
Once you've loaded this stored procedure,

Search

you can write

EXEC [dbo].[DropPrimaryKey] @TableName='someTable'

It’s just that simple. Similar stored procedures can be written to convert fields from
NOT NULL to NULL and do other operation which required a named constraint.
Paul Houle on June 6th 2008 in SQL

Comments (2)

Comments (2)

Login

Sort by: Date Rating Last Activity
Adrian Banks · 292 weeks ago

+1

A better query to find the primary key for the table would be:
SELECT [name] FROM sysobjects WHERE [xtype] = 'PK' AND [parent_obj] = OBJECT_ID(N'[dbo].[' +
@tableName + ']')
This doesn't rely on a naming convention of primary keys' names starting with PK, but instead uses SQL
Server's own data on whether the index is a primary key.
Reply

http://gen5.info/q/2008/06/06/how-to-drop-a-primary-key-in-microsoft-sql-server/[1/16/2014 3:53:20 PM]

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 » How to Drop A Primary Key in Microsoft SQL Server

admin · 292 weeks ago

-1

Thanks Adrian! I tested this and then updated the script. It's nice to see what a wealth of information
is in the system catalog tables.
Reply

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/06/how-to-drop-a-primary-key-in-microsoft-sql-server/[1/16/2014 3:53:20 PM]

Contenu connexe

Plus de Paul Houle

Plus de Paul Houle (20)

Ontology2 Platform Evolution
Ontology2 Platform EvolutionOntology2 Platform Evolution
Ontology2 Platform Evolution
 
Paul houle the supermen
Paul houle   the supermenPaul houle   the supermen
Paul houle the supermen
 
Paul houle what ails enterprise search
Paul houle   what ails enterprise search Paul houle   what ails enterprise search
Paul houle what ails enterprise search
 
Subjective Importance Smackdown
Subjective Importance SmackdownSubjective Importance Smackdown
Subjective Importance Smackdown
 
Extension methods, nulls, namespaces and precedence in c#
Extension methods, nulls, namespaces and precedence in c#Extension methods, nulls, namespaces and precedence in c#
Extension methods, nulls, namespaces and precedence in c#
 
Dropping unique constraints in sql server
Dropping unique constraints in sql serverDropping unique constraints in sql server
Dropping unique constraints in sql server
 
Prefix casting versus as-casting in c#
Prefix casting versus as-casting in c#Prefix casting versus as-casting in c#
Prefix casting versus as-casting in c#
 
Paul houle resume
Paul houle resumePaul houle resume
Paul houle resume
 
Keeping track of state in asynchronous callbacks
Keeping track of state in asynchronous callbacksKeeping track of state in asynchronous callbacks
Keeping track of state in asynchronous callbacks
 
Embrace dynamic PHP
Embrace dynamic PHPEmbrace dynamic PHP
Embrace dynamic PHP
 
Once asynchronous, always asynchronous
Once asynchronous, always asynchronousOnce asynchronous, always asynchronous
Once asynchronous, always asynchronous
 
What do you do when you’ve caught an exception?
What do you do when you’ve caught an exception?What do you do when you’ve caught an exception?
What do you do when you’ve caught an exception?
 
Extension methods, nulls, namespaces and precedence in c#
Extension methods, nulls, namespaces and precedence in c#Extension methods, nulls, namespaces and precedence in c#
Extension methods, nulls, namespaces and precedence in c#
 
Pro align snap 2
Pro align snap 2Pro align snap 2
Pro align snap 2
 
Proalign Snapshot 1
Proalign Snapshot 1Proalign Snapshot 1
Proalign Snapshot 1
 
Text wise technology textwise company, llc
Text wise technology   textwise company, llcText wise technology   textwise company, llc
Text wise technology textwise company, llc
 
Tapir user manager
Tapir user managerTapir user manager
Tapir user manager
 
The Global Performing Arts Database
The Global Performing Arts DatabaseThe Global Performing Arts Database
The Global Performing Arts Database
 
Arxiv.org: Research And Development Directions
Arxiv.org: Research And Development DirectionsArxiv.org: Research And Development Directions
Arxiv.org: Research And Development Directions
 
Commonspot installation at cornell university library
Commonspot installation at cornell university libraryCommonspot installation at cornell university library
Commonspot installation at cornell university library
 

Dernier

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Victor Rentea
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Safe Software
 

Dernier (20)

Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
Modular Monolith - a Practical Alternative to Microservices @ Devoxx UK 2024
 
Corporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptxCorporate and higher education May webinar.pptx
Corporate and higher education May webinar.pptx
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 
Exploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with MilvusExploring Multimodal Embeddings with Milvus
Exploring Multimodal Embeddings with Milvus
 
CNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In PakistanCNIC Information System with Pakdata Cf In Pakistan
CNIC Information System with Pakdata Cf In Pakistan
 
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
Apidays New York 2024 - Passkeys: Developing APIs to enable passwordless auth...
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf[BuildWithAI] Introduction to Gemini.pdf
[BuildWithAI] Introduction to Gemini.pdf
 
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
Biography Of Angeliki Cooney | Senior Vice President Life Sciences | Albany, ...
 
Exploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone ProcessorsExploring the Future Potential of AI-Enabled Smartphone Processors
Exploring the Future Potential of AI-Enabled Smartphone Processors
 
Artificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : UncertaintyArtificial Intelligence Chap.5 : Uncertainty
Artificial Intelligence Chap.5 : Uncertainty
 
Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024Manulife - Insurer Transformation Award 2024
Manulife - Insurer Transformation Award 2024
 
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data DiscoveryTrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
TrustArc Webinar - Unlock the Power of AI-Driven Data Discovery
 
MS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectorsMS Copilot expands with MS Graph connectors
MS Copilot expands with MS Graph connectors
 
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
Navigating the Deluge_ Dubai Floods and the Resilience of Dubai International...
 
presentation ICT roal in 21st century education
presentation ICT roal in 21st century educationpresentation ICT roal in 21st century education
presentation ICT roal in 21st century education
 
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
Apidays New York 2024 - APIs in 2030: The Risk of Technological Sleepwalk by ...
 
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers:  A Deep Dive into Serverless Spatial Data and FMECloud Frontiers:  A Deep Dive into Serverless Spatial Data and FME
Cloud Frontiers: A Deep Dive into Serverless Spatial Data and FME
 

How to drop a primary key in microsoft sql server

  • 1. Generation 5 » How to Drop A Primary Key in Microsoft SQL Server  Subscribe to our RSS Feed | About Us How to Drop A Primary Key in Microsoft SQL Server Search for: One of my pet peeves with Microsoft’s SQL Server is that it requires you to know the name of constraints and indexes that you’re dropping. This isn’t a problem when you’re working with the management studio, because it looks at the database metadata and generates code like ALTER TABLE [dbo].[someTable] DROP CONSTRAINT [PK__someTabl__3214EC07271AA44F] It’s less convenient, however, when you’re writing a set of migration scripts in SQL to implement changes that you make over the database in time. Specifically, if you create the table twice in two different databases, the hexadecimal string in the name of the key will be different — the ALTER TABLE statement will fail when you try to drop the index later, since the name of the key won’t match. Here’s a stored procedure that looks up the name of the primary key in the system catalog and uses dynamic SQL to drop the index: CREATE PROCEDURE [dbo].[DropPrimaryKey] @tableName Varchar(255) AS /* Drop the primary key on @TableName http://gen5.info/q/ Version 1.1 June 9, 2008 */ 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 DECLARE @pkName Varchar(255) SET @pkName= ( SELECT [name] FROM sysobjects WHERE [xtype] = 'PK' AND [parent_obj] = OBJECT_ID(N'[dbo].['+@tableName+N']') ) DECLARE @dropSql varchar(4000) SET @dropSql= 'ALTER TABLE [dbo].['+@tableName+'] DROP CONSTRAINT ['+@PkName+']' EXEC(@dropSql) GO Once you've loaded this stored procedure, Search you can write EXEC [dbo].[DropPrimaryKey] @TableName='someTable' It’s just that simple. Similar stored procedures can be written to convert fields from NOT NULL to NULL and do other operation which required a named constraint. Paul Houle on June 6th 2008 in SQL Comments (2) Comments (2) Login Sort by: Date Rating Last Activity Adrian Banks · 292 weeks ago +1 A better query to find the primary key for the table would be: SELECT [name] FROM sysobjects WHERE [xtype] = 'PK' AND [parent_obj] = OBJECT_ID(N'[dbo].[' + @tableName + ']') This doesn't rely on a naming convention of primary keys' names starting with PK, but instead uses SQL Server's own data on whether the index is a primary key. Reply http://gen5.info/q/2008/06/06/how-to-drop-a-primary-key-in-microsoft-sql-server/[1/16/2014 3:53:20 PM] 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 » How to Drop A Primary Key in Microsoft SQL Server admin · 292 weeks ago -1 Thanks Adrian! I tested this and then updated the script. It's nice to see what a wealth of information is in the system catalog tables. Reply 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/06/how-to-drop-a-primary-key-in-microsoft-sql-server/[1/16/2014 3:53:20 PM]