Saturday, February 23, 2008

SQL Server: ลบ Column ที่ Not Null และมีค่า Default

สำหรับ filed ที่คุณมีการตั้งค่า default ไว้ SQL Server จะไม่ยอมให้ drop โดยตรง เมื่อคุณใช้

alter table Table1 drop column Col1

จะขึ้น error ว่า
Msg 5074, Level 16, State 1, Line 1
The object 'DF__Table1__Col1__35E7E693' is dependent on column 'Col1'.
Msg 4922, Level 16, State 9, Line 1
ALTER TABLE DROP COLUMN Col1 failed because one or more objects access this column.

คุณต้อง

1. แก้ให้ Col1 เป็น null ได้ และไม่มีค่า default
alter table Table1 alter column [Col1] [int] NULL

2. ลบ constraint DF_... ทิ้งไปก่อน
alter table Table1 drop constraint DF__Table1__Col1__1FC39B4A

3. ทีนี้ก็ drop column ได้แล้ว
alter table Table1 drop column Col1

Command(s) completed successfully.