Alter column, add default constraint


Tengo una tabla y una de las columnas es "Date" de tipo datetime. Decidimos agregar una restricción predeterminada a esa columna

Alter table TableName
alter column dbo.TableName.Date default getutcdate() 

Pero esto me da error:

Sintaxis incorrecta cerca de'.'

¿Alguien ve algo obviamente mal aquí, que me falta (aparte de tener un mejor nombre para la columna)

Author: abatishchev, 2010-01-19

5 answers

Prueba esto

alter table TableName 
 add constraint df_ConstraintNAme 
 default getutcdate() for [Date]

Ejemplo

create table bla (id int)

alter table bla add constraint dt_bla default 1 for id



insert bla default values

select * from bla

También asegúrese de nombrar el valor predeterminado constraint..it será un dolor en el cuello dejarlo caer más tarde porque tendrá uno de esos locos nombres generados por el sistema...Consulte también Cómo Nombrar Restricciones Predeterminadas Y Cómo Eliminar Restricciones Predeterminadas Sin Un Nombre En SQL Server

 308
Author: SQLMenace,
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
2010-01-19 17:07:56

Utilizo el procedimiento almacenado a continuación para actualizar los valores predeterminados en una columna.

Elimina automáticamente cualquier valor predeterminado anterior en la columna, antes de agregar el nuevo valor predeterminado.

Ejemplos de uso:

-- Update default to be a date.
exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','Column','getdate()';
-- Update default to be a number.
exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','Column,'6';
-- Update default to be a string. Note extra quotes, as this is not a function.
exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','Column','''MyString''';

Procedimiento almacenado:

SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO

-- Sample function calls:
--exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','ColumnName','getdate()';
--exec [dbol].[AlterDefaultForColumn] '[dbo].[TableName]','Column,'6';
--exec [dbo].[AlterDefaultForColumn] '[dbo].[TableName]','Column','''MyString''';
create PROCEDURE [dbo].[ColumnDefaultUpdate]
    (
        -- Table name, including schema, e.g. '[dbo].[TableName]'
        @TABLE_NAME VARCHAR(100), 
        -- Column name, e.g. 'ColumnName'.
        @COLUMN_NAME VARCHAR(100),
        -- New default, e.g. '''MyDefault''' or 'getdate()'
        -- Note that if you want to set it to a string constant, the contents
        -- must be surrounded by extra quotes, e.g. '''MyConstant''' not 'MyConstant'
        @NEW_DEFAULT VARCHAR(100)
    )
AS 
BEGIN       
    -- Trim angle brackets so things work even if they are included.
    set @COLUMN_NAME = REPLACE(@COLUMN_NAME, '[', '')
    set @COLUMN_NAME = REPLACE(@COLUMN_NAME, ']', '')

    print 'Table name: ' + @TABLE_NAME;
    print 'Column name: ' + @COLUMN_NAME;
    DECLARE @ObjectName NVARCHAR(100)
    SELECT @ObjectName = OBJECT_NAME([default_object_id]) FROM SYS.COLUMNS
    WHERE [object_id] = OBJECT_ID(@TABLE_NAME) AND [name] = @COLUMN_NAME;

    IF @ObjectName <> '' 
    begin
        print 'Removed default: ' + @ObjectName;
        --print('ALTER TABLE ' + @TABLE_NAME + ' DROP CONSTRAINT ' + @ObjectName)
        EXEC('ALTER TABLE ' + @TABLE_NAME + ' DROP CONSTRAINT ' + @ObjectName)
    end

    EXEC('ALTER TABLE ' + @TABLE_NAME + ' ADD  DEFAULT (' + @NEW_DEFAULT + ') FOR ' + @COLUMN_NAME)
    --print('ALTER TABLE ' + @TABLE_NAME + ' ADD  DEFAULT (' + @NEW_DEFAULT + ') FOR ' + @COLUMN_NAME)
    print 'Added default of: ' + @NEW_DEFAULT;
END

Errores este procedimiento almacenado elimina

Si intenta agregar un valor predeterminado a una columna cuando ya existe, obtendrá el siguiente error (algo que nunca verá si usa este proc almacenado):

-- Using the stored procedure eliminates this error:
Msg 1781, Level 16, State 1, Line 1
Column already has a DEFAULT bound to it.
Msg 1750, Level 16, State 0, Line 1
Could not create constraint. See previous errors.
 7
Author: Contango,
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-04-09 12:20:47

Puede envolver las palabras reservadas entre corchetes para evitar este tipo de errores:

dbo.TableName.[Date]
 6
Author: Ray,
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
2012-11-12 20:28:15

En realidad tienes que Hacer Como el siguiente Ejemplo, que ayudará a Resolver el Problema...

drop table ABC_table

create table ABC_table
(
    names varchar(20),
    age int
)

ALTER TABLE ABC_table
ADD CONSTRAINT MyConstraintName
DEFAULT 'This is not NULL' FOR names

insert into ABC(age) values(10)

select * from ABC
 5
Author: Ajit Kumar KV,
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-28 08:57:23

Está especificando el nombre de la tabla dos veces. La parte ALTER TABLE nombra la tabla. Tratar: Modificar el nombre de la tabla alter column [Date] default getutcdate ()

 0
Author: user2938266,
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-09-14 14:06:03