Cómo establecer un valor predeterminado para una columna existente


Esto no funciona en SQL Server 2008:

ALTER TABLE Employee ALTER COLUMN CityBorn SET DEFAULT 'SANDNES'

El error es:

Sintaxis incorrecta cerca de la palabra clave 'SET'.

¿Qué estoy haciendo mal?

Author: gotqn, 2011-07-22

12 answers

Esto funcionará en SQL Server:

ALTER TABLE Employee ADD CONSTRAINT DF_SomeName DEFAULT N'SANDNES' FOR CityBorn;
 448
Author: Yuck,
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
2011-07-22 14:48:28
ALTER TABLE Employee ADD DEFAULT 'SANDNES' FOR CityBorn
 137
Author: hoodaticus,
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
2011-07-22 14:46:29

No se puede usar alter column para eso, use add en su lugar

ALTER TABLE Employee 
ADD DEFAULT('SANDNES') FOR CityBorn
 42
Author: Carlos Quintanilla,
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
2011-07-22 14:53:07

La forma correcta de hacer esto es la siguiente:

  1. Ejecute el comando:

    sp_help [table name] 
    
  2. Copie el nombre del CONSTRAINT.

  3. Suelta el DEFAULT CONSTRAINT:

    ALTER TABLE [table name] DROP [NAME OF CONSTRAINT] 
    
  4. Ejecute el siguiente comando:

    ALTER TABLE [table name] ADD DEFAULT [DEFAULT VALUE] FOR [NAME OF COLUMN]
    
 23
Author: user3310402,
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
2015-04-28 18:36:32

La solución de Hoodaticus fue perfecta, gracias, pero también necesitaba que se pudiera volver a ejecutar y encontré esta manera de verificar si se había hecho...

IF EXISTS(SELECT * FROM information_schema.columns 
           WHERE table_name='myTable' AND column_name='myColumn' 
             AND Table_schema='myDBO' AND column_default IS NULL) 
BEGIN 
  ALTER TABLE [myDBO].[myTable] ADD DEFAULT 0 FOR [myColumn] --Hoodaticus
END
 9
Author: Dave,
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-02-03 10:08:45

Hay dos escenarios donde el valor predeterminado para una columna podría cambiarse,

  1. En el momento de crear la tabla
  2. Modificar la columna existente para una tabla existente.

  1. En el momento de crear la tabla / crear una nueva columna.

Consulta

create table table_name
(
    column_name datatype default 'any default value'
);
  1. Modificar la columna existente para una tabla existente

En este caso my SQL server no permite modificar el valor de restricción predeterminado existente. Así que para cambiar el valor predeterminado necesidad de eliminar la restricción predeterminada generada por el sistema existente o generada por el usuario. Y después de que el valor predeterminado se puede establecer para una columna en particular.

Siga algunos pasos:

  1. Enumere todas las restricciones de valor predeterminadas existentes para las columnas.

Ejecute este procedimiento de base de datos del sistema, toma el nombre de la tabla como parámetro. Devuelve la lista de todas las restricciones para todas las columnas dentro de la tabla.

execute [dbo].[sp_helpconstraint] 'table_name'
  1. Soltar la restricción predeterminada existente para una columna.

Sintaxis:

alter table 'table_name' drop constraint 'constraint_name'
  1. Agregue una nueva restricción de valor predeterminado para esa columna:

Sintaxis:

alter table 'table_name' add default 'default_value' for 'column_name'

Saludos @!!!

 5
Author: Sunil Sharma,
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
2015-02-24 05:25:14
ALTER TABLE [dbo].[Employee] ADD  DEFAULT ('N') FOR [CityBorn]
 3
Author: steave,
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
2014-01-27 13:52:42

Acabo de encontrar 3 sencillos pasos para alterar la columna ya existente que era null antes de

update   orders
set BasicHours=0 where BasicHours is null

alter table orders 
add default(0) for BasicHours

alter table orders 
alter  column CleanBasicHours decimal(7,2) not null 
 3
Author: David Fawzy,
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-12-13 10:10:22

Intenta seguir el comando;

ALTER TABLE Person11
ADD CONSTRAINT col_1_def
DEFAULT 'This is not NULL' FOR Address
 2
Author: Hasna Ashraf,
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
2015-09-15 11:25:47

Como la respuesta de Yuck con una comprobación para permitir que el script se ejecute más de una vez sin error. (menos cadenas de código/personalizadas que usando information_schema.columnas)

IF object_id('DF_SomeName', 'D') IS NULL BEGIN
    Print 'Creating Constraint DF_SomeName'
   ALTER TABLE Employee ADD CONSTRAINT DF_SomeName DEFAULT N'SANDNES' FOR CityBorn;
END
 1
Author: ScottFoster1000,
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-06-02 05:01:15

Restricciones de primera caída

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

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)

Segundo crear valor predeterminado

ALTER TABLE [table name] ADD DEFAULT [default value] FOR [column name]
 0
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:57:18

En caso de que ya exista una restricción con su nombre predeterminado:

-- Drop existing default constraint on Employee.CityBorn
DECLARE @default_name varchar(256);
SELECT @default_name = [name] FROM sys.default_constraints WHERE parent_object_id=OBJECT_ID('Employee') AND COL_NAME(parent_object_id, parent_column_id)='CityBorn';
EXEC('ALTER TABLE Employee DROP CONSTRAINT ' + @default_name);

-- Add default constraint on Employee.CityBorn
ALTER TABLE Employee ADD CONSTRAINT df_employee_1 DEFAULT 'SANDNES' FOR CityBorn;
 0
Author: tibx,
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-08-17 12:24:43