1
----------------------------------------------
DepartmentCode  varchar(30) AllowNulls
----------------------------------------------

Does anyone know how to change the datatype of a column in SQL 2008? This is the column I want to alter but when I try this query,

ALTER TABLE SystemDepartment ALTER COLUMN DepartmentCode smallint NOT NULL

I get the following error:

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

My question is how to force my query to cope with it? and I also would like to set this column as primary key and identity

Cute Bear
  • 3,223
  • 13
  • 44
  • 69
  • To add to the responses below, first you need to get the ID of the PK. This is how I do it: SELECT name FROM sys.key_constraints WHERE type = 'PK' AND OBJECT_NAME(parent_object_id) = N'SystemDepartment'; That returns the ID of the PK which you can then use as detailed by Hardik below. – Tim Bostwick Aug 12 '14 at 23:50

3 Answers3

6

You will first need to drop Primary Key constraint.

ALTER TABLE SystemDepartment DROP CONSTRAINT PK_SYSTEMDEPARTMENT

Then only you can ALTER that column.

You can not force existing column to identity. In this case you will need to add new column with identity and then do sp_rename to old name.

Himanshu
  • 31,810
  • 31
  • 111
  • 133
sqlhdv
  • 254
  • 1
  • 7
  • You can alter an existing column to be `IDENTITY` using [`ALTER TABLE ... SWITCH`](http://stackoverflow.com/questions/6084572/how-to-set-auto-increment-after-creating-a-table-without-any-data-loss/6086661#6086661) but couldn't do the datatype change from `varchar` to `int` without dropping the PK. – Martin Smith Sep 03 '12 at 08:58
0

If your constraint is on a user type, then don't forget to see if there is a Default Constraint, usually something like DF__TableName__ColumnName__6BAEFA67, if so then you will need to drop the Default Constraint, like this:

ALTER TABLE TableName DROP CONSTRAINT [DF__TableName__ColumnName__6BAEFA67]

For more info see the comments by the brilliant Aaron Bertrant on this answer.

Community
  • 1
  • 1
Serj Sagan
  • 28,927
  • 17
  • 154
  • 183
-1

Try this ,

as you told you are getting primary key constraint error , 1st you have to drop the primary key and use the following query ,

    ALTER TABLE SystemDepartment MODIFY DepartmentCode int(3)

Thanks,

Venkat.

Venaikat
  • 197
  • 2
  • 5
  • 20