Search code examples
sqlt-sqlsql-server-2014

Naming a default constraint


I'm trying to create a default constraint here, but the system is generating a weird name for it. If I want to name it df_MY_TABLE_GUID or something, how could I specify that name be used?

ALTER TABLE MY_TABLE 
    ADD MY_GUID uniqueidentifier NOT NULL 
        CONSTRAINT uq_MY_TABLE_GUID UNIQUE (MY_TABLE_GUID) 
        DEFAULT NEWID() WITH VALUES

Solution

  • Just specify the constraint name with the full syntax, like the UNIQUE in your example:

    ALTER TABLE MY_TABLE ADD MY_GUID UNIQUEIDENTIFIER NOT NULL
        CONSTRAINT uq_MY_TABLE_GUID UNIQUE (MY_TABLE_GUID)
        CONSTRAINT df_MY_TABLE_GUID DEFAULT NEWID() WITH VALUES ;
    

    As a matter of routine, I always prefer and encourage to always name every single constraint I create, for the sake of easy reference latter on.