开发者

Adding a new primary key to existing table

开发者 https://www.devze.com 2023-01-19 05:26 出处:网络
I have table with following details Table name EMPLOYEE and columns EMPID 开发者_开发知识库(PK smallint not null)

I have table with following details

Table name EMPLOYEE and columns

EMPID 开发者_开发知识库(PK smallint not null)
EMPNAME (varchar 256 not null)
ORG (FK smallint not null)
FUNCTION (FK smallint not null)
EFF_DATE (datetime null)
AUDIT_ID (varchar null)

Now I have to add an extra coulmn to this table ADD_UID and make it also primary key

I am using this query but failing.

ALTER TABLE CVADMIN.EMPLOYEE
 ADD ADD_UID  varchar(32) NULL,
 CONSTRAINT PK_EMPLOYEE PRIMARY KEY [NON]CLUSTERED (ADD_UID)
go

Table 'EMPLOYEE' already has a primary key defined on it.

EDIT

The idea here is the new column should be unique so that if it fails I can throw _KEY_VIOLATION so that some code manipulation is done


To add a unique constraint (which is additional to the primary key) do this:

ALTER TABLE EMPLOYEE ADD CONSTRAINT uc_UID UNIQUE (ADD_UID)


We can add new columns on any tables by alter statement but added column can be null and you know primary key does not accept null on any column.
Therefore we can not create primary key on the newly added column by alter statement.

0

精彩评论

暂无评论...
验证码 换一张
取 消