更改列,添加默认约束


185

我有一张桌子,其中一列是日期时间类型的“日期”。我们决定向该列添加默认约束

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

但这给我错误:

'。'附近的语法不正确

有人在这里看到任何明显错误的地方吗?


11
不要将类型或关键字用作列名!
JonH 2010年

8
是的,同意-“有人在这里看到任何明显错误的地方吗,我想念这个(而不是为该栏起个更好的名字)”
ram 2010年

Answers:


349

试试这个

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

create table bla (id int)

alter table bla add constraint dt_bla default 1 for id



insert bla default values

select * from bla

还请确保您命名默认约束..稍后将其删除很麻烦,因为它将具有那些由系统生成的疯狂名称之一...另请参见如何命名默认约束和如何在不使用默认约束的情况下删除默认约束。 SQL Server中的名称


7

您可以将保留字括在方括号中,以避免出现此类错误:

dbo.TableName.[Date]

1
对于列名使用保留字似乎是一个非常糟糕的主意。
Norbert Norbertson

4
似乎可以,但事实并非如此。我成功地使用它们自2004年以来:)
克特林Rădoi

7

我使用下面的存储过程来更新列的默认设置。

在添加新默认值之前,它将自动删除该列上的所有先前默认值。

用法示例:

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

存储过程:

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

此存储过程消除的错误

如果您尝试在已经存在的列中添加默认值,则会收到以下错误(如果使用此存储过程,将永远看不到):

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

5

实际上,您必须在下面的示例中做“喜欢”,这将有助于解决问题...

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

这仅用于练习,不能在现实中使用
Tr Longng Long


By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.