¿Cómo se elimina un valor predeterminado de una columna de una tabla?


¿Cómo se altera una columna para eliminar el valor predeterminado?

La columna fue creada con:

 ALTER table sometable Add somecolumn nchar(1) NOT NULL DEFAULT 'N'

Y luego alterada con:

 alter table sometable alter column somecolumn nchar(1) null

Que permite valores nulos, pero el valor por defecto permanece. ¿Cómo se puede quitar?

Author: Yishai, 2009-09-02

6 answers

Es una restricción predeterminada, debe realizar una:

ALTER TABLE
DROP CONSTRAINT ConstraintName

Si no especificó un nombre cuando creó la restricción, entonces SQL Server creó uno para usted. Puede usar SQL Server Management Studio para encontrar el nombre de la restricción navegando hasta la tabla, abriendo su nodo de árbol y, a continuación, abriendo el nodo de restricciones.

Si no recuerdo mal, la restricción se llamará algo como DF_SomeStuff_ColumnName.

EDITAR: La respuesta de Josh W. contiene un enlace a SO question que muestra cómo encontrar el nombre de restricción generado automáticamente usando SQL en lugar de usar la interfaz de Management Studio.

 33
Author: Dan Rigby,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-23 10:31:04

Esto es lo que se me ocurrió (antes de ver a Josh W. responder, bueno, en realidad lo vi, pero lo leí tan rápido que lo entendí mal):

declare @name nvarchar(100)
select @name = [name] from sys.objects where type = 'D' and parent_object_id = object_id('sometable')

if (@name is not null)
  begin
     exec ('alter table [sometable] drop constraint [' + @name +']')
  end

La ventaja que tengo aquí es que sé que solo hay una restricción de este tipo en toda la mesa. Si hubiera habido dos, bueno, supongo que es por eso que se supone que debe nombrarlos ;).

(El problema es que se trata de una modificación hecha a 10 bases de datos de clientes diferentes, por lo que no hay un nombre consistente para poner en un script)

 12
Author: Yishai,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-01-19 11:50:12

Si no conoce las restricciones nombre

DECLARE @ConstraintName nvarchar(200)
SELECT @ConstraintName = Name FROM SYS.DEFAULT_CONSTRAINTS
WHERE PARENT_OBJECT_ID = OBJECT_ID('__TableName__')
AND PARENT_COLUMN_ID = (SELECT column_id FROM sys.columns
                        WHERE NAME = N'__ColumnName__'
                        AND object_id = OBJECT_ID(N'__TableName__'))
IF @ConstraintName IS NOT NULL
EXEC('ALTER TABLE __TableName__ DROP CONSTRAINT ' + @ConstraintName)

Https://stackoverflow.com/a/13715343/2547164

 6
Author: Mise,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-03-20 19:54:23
select name from sys.default_constraints where name like '%first_3_chars_of_field_name%'

Encuentra tu restricción y usa DROP CONSTRAINT para soltarla. O ejecute un bucle cursor / while para soltar todos los valores predeterminados similares en la base de datos.

 4
Author: Roman,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-09-14 12:20:34

Si está utilizando SQL Server Management Studio esto es bastante fácil.

Si hay varias restricciones asociadas con la tabla y no desea eliminarlas todas, haga clic con el botón derecho en la restricción y seleccione "Script Cnstraint as- > CREATE to - > New Query Editor Window". Esto le mostrará el código que creó la restricción, incluido el nombre de la columna y el valor predeterminado.

A continuación, haga clic con el botón derecho en la restricción que desea eliminar y seleccione Eliminar.

 0
Author: Mike Godin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-09-05 14:14:44
alter table <tablename> drop constraint <constraintname>

Si no conoce el nombre de la restricción, puede usar sql server manangement studio para verificar el nombre de la restricción .... espero que esto ayude.

 -2
Author: Daniyal Awan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-07-31 06:05:31