0

I just created a table as below in MS SQL

create table Employee 
(emp_id smallint not null,
employee_name varchar (30) not null,
salary money not null,
department varchar(30),
address varchar(40),
primary key(emp_id)
)

After creating the table, I feel like auto populating the emp_id column( using Identity). So, I was trying to drop the column emp_id as below:

alter table Employee 
drop column emp_id

Even though, I haven't inserted any rows in the table yet, I am getting the error

Msg 5074, Level 16, State 1, Line 1 The object 'PK__Employee__1299A86183CA4FBC' is dependent on column 'emp_id'. Msg 4922, Level 16, State 9, Line 1 ALTER TABLE DROP COLUMN emp_id failed because one or more objects access this column.

Please help!!!

6
  • HI it is because the column you are doping has been referenced in other table . If you really want to drop it please first drop the constraint and then drop the column . Commented Jan 17, 2017 at 8:41
  • 2
    emp_id is your primary key as in your create table query primary key(emp_id) so you should drop that Primary Key constraint before drop that column Commented Jan 17, 2017 at 8:43
  • 1
    Possible duplicate of How to drop column with constraint? Commented Jan 17, 2017 at 8:50
  • Thanks Yashveer..I did the same and it worked.. Commented Jan 17, 2017 at 8:53
  • 1
    In fact there is 43 question with "ALTER TABLE DROP COLUMN failed because one or more objects access this column.". Commented Jan 17, 2017 at 9:01

2 Answers 2

2

Something like this can help .

   ALTER TABLE Employee   
   DROP CONSTRAINT PK__Employee__1299A86183CA4FBC; 


   alter table Employee 
   drop column emp_id
Sign up to request clarification or add additional context in comments.

3 Comments

So the Idea is first drop all constraint like primary keys / FK etc and then alter the table
NOTE: When re-adding the column, you'd need to re-add the PK as well.
@CraigYoung :- Thanks I missed to inform that it will make answer more useful .
0

I solved the problem by executing below query: I need to remove a column and all the entries from that column to free my DB size my initial table structure is as shown below:

CREATE TABLE words(_id,word,synonyms,favorite,history,updDate)

And I wanted the table in below form

CREATE TABLE words(_id,word,favorite,history,updDate)

So I executed below query and it removed "synonyms" column

BEGIN TRANSACTION;
CREATE TEMPORARY TABLE t1_backup(_id,word,favorite,history,updDate);
INSERT INTO t1_backup SELECT _id,word,favorite,history,updDate FROM words;
DROP TABLE words;
CREATE TABLE words(_id,word,favorite,history,updDate);
INSERT INTO words SELECT _id,word,favorite,history,updDate FROM t1_backup;
DROP TABLE t1_backup
COMMIT;

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.