[sql-server] Alter column, add default constraint

I have a table and one of the columns is "Date" of type datetime. We decided to add a default constraint to that column

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

but this gives me error:

Incorrect syntax near '.'

Does anyone see anything obviously wrong here, which I am missing (other than having a better name for the column)

The answer is


you can wrap reserved words in square brackets to avoid these kinds of errors:

dbo.TableName.[Date]

I confirm like the comment from JohnH, never use column types in the your object names! It's confusing. And use brackets if possible.

Try this:

ALTER TABLE [TableName]
ADD  DEFAULT (getutcdate()) FOR [Date]; 

Actually you have to Do Like below Example, which will help to Solve the Issue...

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

You're specifying the table name twice. The ALTER TABLE part names the table. Try: Alter table TableName alter column [Date] default getutcdate()


I use the stored procedure below to update the defaults on a column.

It automatically removes any prior defaults on the column, before adding the new default.

Examples of usage:

-- 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''';

Stored procedure:

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

Errors this stored procedure eliminates

If you attempt to add a default to a column when one already exists, you will get the following error (something you will never see if using this stored proc):

-- 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.

alter table TableName drop constraint DF_TableName_WhenEntered

alter table TableName add constraint DF_TableName_WhenEntered default getutcdate() for WhenEntered


Examples related to sql-server

Passing multiple values for same variable in stored procedure SQL permissions for roles Count the Number of Tables in a SQL Server Database Visual Studio 2017 does not have Business Intelligence Integration Services/Projects ALTER TABLE DROP COLUMN failed because one or more objects access this column Create Local SQL Server database How to create temp table using Create statement in SQL Server? SQL Query Where Date = Today Minus 7 Days How do I pass a list as a parameter in a stored procedure? SQL Server date format yyyymmdd

Examples related to sql-server-2008

Violation of PRIMARY KEY constraint. Cannot insert duplicate key in object How to Use Multiple Columns in Partition By And Ensure No Duplicate Row is Returned SQL Server : How to test if a string has only digit characters Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query Get last 30 day records from today date in SQL Server How to subtract 30 days from the current date using SQL Server Calculate time difference in minutes in SQL Server SQL Connection Error: System.Data.SqlClient.SqlException (0x80131904) SQL Server Service not available in service list after installation of SQL Server Management Studio How to delete large data of table in SQL without log?

Examples related to tsql

Passing multiple values for same variable in stored procedure Count the Number of Tables in a SQL Server Database Change Date Format(DD/MM/YYYY) in SQL SELECT Statement Stored procedure with default parameters Format number as percent in MS SQL Server EXEC sp_executesql with multiple parameters SQL Server after update trigger How to compare datetime with only date in SQL Server Text was truncated or one or more characters had no match in the target code page including the primary key in an unpivot Printing integer variable and string on same line in SQL

Examples related to alter-table

How to add a boolean datatype column to an existing table in sql? how to modify the size of a column MySQL: ALTER TABLE if column not exists Hive Alter table change Column Name Alter table to modify default value of column Rename column SQL Server 2008 How to delete a column from a table in MySQL Altering column size in SQL Server ALTER TABLE on dependent column ALTER TABLE to add a composite primary key

Examples related to alter-column

ALTER TABLE on dependent column When increasing the size of VARCHAR column on a large table could there be any problems? How to alter a column's data type in a PostgreSQL table? How to ALTER multiple columns at once in SQL Server Change a Nullable column to NOT NULL with Default Value Alter column, add default constraint Altering a column: null to not null