Sunday 1 June 2014

How to alter primary key column for existing table in sql server 2008

Hi friends,in this article i will explain about How to alter primary key column for existing table in SQL Server 2008.
I already explained about How to Get List of Stored Procedures based on table name search, using sql server 2008?,Differences and Similarities Between LEN and DATALENGTH Functions in SQL Server and Common Table Expressions(CTE) in SQL SERVER 2008

Create table User_Details as shown below.
CREATE TABLE [dbo].[Users_Details](
            [Username] [nchar](20) NOT NULL,
            [Password] [nchar](20) NOT NULL,
            [Email] [nchar](30) NULL,
            [Mobile] [nchar](15) NULL,
            [Address] [nchar](100) NULL,
            [USER_ID] [int] IDENTITY(1,1) NOT NULL,
            [Gender] [varchar](15) NULL,
            [Country] [varchar](50) NULL,
    CONSTRAINT [PK_Username] PRIMARY KEY CLUSTERED
    (
            [Username] ASC
    )
    )

When you alter the column as
ALTER TABLE Users_details
ALTER COLUMN USERname NVARCHAR(100)

and execute it shows below error.Because Username column contains Primary Key.
Msg 5074, Level 16, State 1, Line 1
The object 'PK_Username' is dependent on column 'Username'.
Msg 4922, Level 16, State 9, Line 1
ALTER TABLE ALTER COLUMN Username failed because one or more objects access this column.

First Drop the Primary Key Constraint and alter table and add  Primary Key Constraint 
ALTER TABLE Users_Details
DROP CONSTRAINT PK_Username

ALTER TABLE Users_Details
ALTER COLUMN Username NVARCHAR(100) NOT NULL

ALTER TABLE Users_Details
ADD CONSTRAINT PK_Username PRIMARY KEY(Username)

No comments:

Post a Comment

© 2012-2018 Aspdotnet-Kishore.blogspot.com. All Rights Reserved.
The content is copyrighted to Kishore and may not be reproduced on other websites without permission from the owner.