Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sql server drop default syntax error

I am trying to drop the default value on a bit column, I have set it wrong and I want to do it again correctly. However, when I write:

ALTER TABLE Person
ALTER COLUMN tsHomePref DROP DEFAULT;

I get a 'incorrect syntax near keyword default error' and I don't know why

I want to drop the column and then build it again

ALTER TABLE Person
ADD COLUMN tsHomePref bit NOT NULL DEFAULT 0;

So, why won't it let me 'drop' the default value?

Thanks R.

like image 447
flavour404 Avatar asked Jan 21 '23 20:01

flavour404


2 Answers

You would need to do

ALTER TABLE Person 
    DROP CONSTRAINT DF__Person__tsHomePr__05BA7BDB

It helps if you use a consistent naming convention for these so you don't have to look in the system tables to get the name first.

like image 68
Martin Smith Avatar answered Mar 05 '23 12:03

Martin Smith


If you don't know the name of the constraint ( as I didn't know today when searching for a solution to the same problem ), you can use the following for Ms Sqlserver:

DECLARE @defname VARCHAR(100), @cmd VARCHAR(1000)
SET @defname =
   (SELECT name FROM sysobjects so
     JOIN sysconstraints sc ON so.id = sc.constid
   WHERE object_name(so.parent_obj) = 'TableName'
     AND sc.colid = 
         (SELECT colid FROM syscolumns WHERE id = object_id('dbo.TableName') AND name = 'FieldName'))
    SET @cmd = 'ALTER TABLE TableName DROP CONSTRAINT ' + @defname
   EXEC(@cmd)
GO 

This worked in my case. Hope it helps others as well.

like image 41
Edelcom Avatar answered Mar 05 '23 12:03

Edelcom