Can default object names be changed?Can the default minimum date range for 'datetime' be changed in SQL Server 2008 R2?Who and when were changed Database default location settings?Slow delete caused by many foreign keysNormalized Data Store - Confused with prefixes to useWhy should I “Avoid partitioning dimension tables” on SQL Server?SMO, SSMS are slow for management of SQL Server in Docker when connecting to localhostSQL Server 2017 Management Data Warehouse: collection_set_1 not working due to database triggerHow to know which instance is default in Configuration Manager if default port number is changed?Why can't object names start with a number?

one-liner vs script

Why are engines with carburetors hard to start in cold weather?

Why is the logical NOT operator in C-style languages "!" and not "~~"?

A sentient carnivorous species trying to preserve life. How could they find a new food source?

Looking for PC graphics demo software from the early 90s called "Unreal"

Sanitise a high score table

What does IKEA-like mean?

Can I use I2C over 2m cables?

Why did a young George Washington sign a document admitting to assassinating a French military officer?

Does "Op. cit." stand for "opus citatum" or "opere citato"?

Why does unique_ptr<Derived> implicitly cast to unique_ptr<Base>?

Relation between signal processing and control systems engineering?

Can I color text by using an image, so that the color isn't flat?

Would it be easier to colonise a living world or a dead world?

What do you call the fallacy of thinking that some action A will guarantee some outcome B, when in reality B depends on multiple other conditions?

How could "aggressor" pilots fly foreign aircraft without speaking the language?

How to make "acts of patience" exciting?

Does the Creighton Method of Natural Family Planning have a failure rate of 3.2% or less?

How to copy the path of current directory in ubuntu 18.04

Are there any privately owned large commercial airports?

Water Bottle Rocket Thrust - two calculation methods not matching

Should a grammatical article be a part of a web link anchor

Can default object names be changed?

What is the meaning of "log" in this sentence?



Can default object names be changed?


Can the default minimum date range for 'datetime' be changed in SQL Server 2008 R2?Who and when were changed Database default location settings?Slow delete caused by many foreign keysNormalized Data Store - Confused with prefixes to useWhy should I “Avoid partitioning dimension tables” on SQL Server?SMO, SSMS are slow for management of SQL Server in Docker when connecting to localhostSQL Server 2017 Management Data Warehouse: collection_set_1 not working due to database triggerHow to know which instance is default in Configuration Manager if default port number is changed?Why can't object names start with a number?






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty
margin-bottom:0;









2















Sooner or later, a db developer will come across, and possibly use, a naming scheme for many objects like foreign keyes, default constraints etc.



Let's consider this example: Name all foreign keys as:
FK__[name of source table]__[name of source col]__ref__[name of master table]__[name of master column]



What kind of parametrization/external programs could be used to achieve having such a name as default, when for example using a create table statements which mentions the fk but does not explicitly provide a constraint name?










share|improve this question





















  • 1





    I think what you are wanting is policy based management. This isn't an external program though.

    – scsimon
    8 hours ago

















2















Sooner or later, a db developer will come across, and possibly use, a naming scheme for many objects like foreign keyes, default constraints etc.



Let's consider this example: Name all foreign keys as:
FK__[name of source table]__[name of source col]__ref__[name of master table]__[name of master column]



What kind of parametrization/external programs could be used to achieve having such a name as default, when for example using a create table statements which mentions the fk but does not explicitly provide a constraint name?










share|improve this question





















  • 1





    I think what you are wanting is policy based management. This isn't an external program though.

    – scsimon
    8 hours ago













2












2








2








Sooner or later, a db developer will come across, and possibly use, a naming scheme for many objects like foreign keyes, default constraints etc.



Let's consider this example: Name all foreign keys as:
FK__[name of source table]__[name of source col]__ref__[name of master table]__[name of master column]



What kind of parametrization/external programs could be used to achieve having such a name as default, when for example using a create table statements which mentions the fk but does not explicitly provide a constraint name?










share|improve this question
















Sooner or later, a db developer will come across, and possibly use, a naming scheme for many objects like foreign keyes, default constraints etc.



Let's consider this example: Name all foreign keys as:
FK__[name of source table]__[name of source col]__ref__[name of master table]__[name of master column]



What kind of parametrization/external programs could be used to achieve having such a name as default, when for example using a create table statements which mentions the fk but does not explicitly provide a constraint name?







sql-server






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited 7 hours ago









a_horse_with_no_name

46.8k9 gold badges95 silver badges126 bronze badges




46.8k9 gold badges95 silver badges126 bronze badges










asked 8 hours ago









George MenoutisGeorge Menoutis

1875 bronze badges




1875 bronze badges










  • 1





    I think what you are wanting is policy based management. This isn't an external program though.

    – scsimon
    8 hours ago












  • 1





    I think what you are wanting is policy based management. This isn't an external program though.

    – scsimon
    8 hours ago







1




1





I think what you are wanting is policy based management. This isn't an external program though.

– scsimon
8 hours ago





I think what you are wanting is policy based management. This isn't an external program though.

– scsimon
8 hours ago










2 Answers
2






active

oldest

votes


















2

















What kind of parametrization/external programs could be used to
achieve having such a name as default, when for example using a create
table statements which mentions the fk but does not explicitly provide
a constraint name?




There's no way to change the default name generated when the DDL doesn't contain a name. The only thing you can do is to run a batch process to identify non-compliant objects and perhaps drop and recreate them.






share|improve this answer
































    2
















    If you want to discourage creation of auto-named constraints, you can do it using database-level DDL trigger for CREATE_TABLE and ALTER_TABLE events.



    Such as, for example



    CREATE TRIGGER [CheckConstraintsNaming] ON DATABASE
    FOR CREATE_TABLE, ALTER_TABLE
    AS
    BEGIN
    SET NOCOUNT ON;

    DECLARE @event xml, @e_type varchar(30), @s_name sysname, @o_name sysname, @o_id int, @is_filetable bit;
    SET @event = EVENTDATA();
    SET @e_type = @event.value('(/EVENT_INSTANCE/EventType/text())[1]', 'varchar(30)');
    SET @s_name = @event.value('(/EVENT_INSTANCE/SchemaName/text())[1]', 'sysname');
    SET @o_name = @event.value('(/EVENT_INSTANCE/ObjectName/text())[1]', 'sysname');
    SELECT @o_id = t.object_id, @is_filetable = t.is_filetable
    FROM sys.tables t
    JOIN sys.schemas s ON s.schema_id = t.schema_id
    WHERE s.name = @s_name AND t.name = @o_name;

    IF @is_filetable = 1
    RETURN;

    DECLARE @msgConstraints nvarchar(max), @msg nvarchar(max);

    SELECT
    @msgConstraints = STRING_AGG(QUOTENAME(c.name), CHAR(13) + CHAR(10))
    FROM (
    SELECT name FROM sys.key_constraints WHERE parent_object_id = @o_id AND is_system_named = 1
    UNION ALL
    SELECT name FROM sys.foreign_keys WHERE parent_object_id = @o_id AND is_system_named = 1
    UNION ALL
    SELECT name FROM sys.check_constraints WHERE parent_object_id = @o_id AND is_system_named = 1
    UNION ALL
    SELECT name FROM sys.default_constraints WHERE parent_object_id = @o_id AND is_system_named = 1
    ) c(name)
    WHERE @e_type = 'CREATE_TABLE'
    OR @e_type = 'ALTER_TABLE'
    AND @event.exist('/EVENT_INSTANCE/AlterTableActionList/Create/Constraints/Name[text()=sql:column("c.name")]') = 1;

    IF @msgConstraints IS NULL OR @msgConstraints = ''
    RETURN;

    SET @msg = 'Table ' + QUOTENAME(@s_name) + '.' + QUOTENAME(@o_name) + ' is being '
    + LOWER(LEFT(@e_type, 5)) + 'ed with one or more auto named constraints:'
    + CHAR(13) + CHAR(10) + @msgConstraints
    + CHAR(13) + CHAR(10) + 'Please specify constraint names explicitly.';

    THROW 51011, @msg, 1;
    ROLLBACK TRANSACTION;
    END
    GO


    Once you have it in database, things like



    CREATE TABLE TableName
    (
    id int NOT NULL,
    parent_id int NULL,
    name varchar(20) NOT NULL,
    dateCreated datetime NOT NULL DEFAULT (GETDATE()),
    value1 float NOT NULL,
    value2 tinyint NOT NULL,
    PRIMARY KEY (ID),
    FOREIGN KEY (parent_id) REFERENCES TableName,
    UNIQUE (name),
    CHECK ((value1 BETWEEN 0 AND 1) AND (value2 IN (1, 2, 4, 8)))
    );


    (and equivalent ALTER) will not be allowed.



    The error message thrown




    Msg 51011, Level 16, State 1, Procedure ConstraintNameCheck, Line 45
    [Batch Start Line 50]

    Table [dbo].[TableName] is being created with one or more auto named constraints:

    [PK__TableNam__3213E83FB1491772]

    [UQ__TableNam__72E12F1BE94335EB]

    [FK__TableName__paren__316D4A39]

    [CK__TableName__32616E72]

    [DF__TableName__dateC__30792600]

    Please specify constraint names explicitly.




    will remind you or your colleague to name constraints explicitly. It can be modified to suggest the "right" name additionally.




    Those who want to see it as a database option in future releases of SQL Server, such as



    ALTER DATABASE [DbName]
    SET CONSTRAINT_NAMING = EXPLICIT ;


    can cast a vote for my initiative here.






    share|improve this answer



























    • I like this, but as coded is disallows all CREATE TABLE and ALTER TABLE for any tables which already have system-named constraints.

      – David Browne - Microsoft
      6 hours ago











    • @DavidBrowne-Microsoft, hmm, I need to think if it can be addressed or not. But I must say that I never suffered from it, because of I usually normalize auto-named constraints (via batch process as you specified in your answer) and then trigger is added to guard against such things. It also has drawbacks if there is memory-optimized stuff in the database. I will try to amend answer later to include drawbacks explanation.

      – i-one
      5 hours ago











    • I'm not sure it needs to be changed. Just pointing that out.

      – David Browne - Microsoft
      4 hours ago












    Your Answer








    StackExchange.ready(function()
    var channelOptions =
    tags: "".split(" "),
    id: "182"
    ;
    initTagRenderer("".split(" "), "".split(" "), channelOptions);

    StackExchange.using("externalEditor", function()
    // Have to fire editor after snippets, if snippets enabled
    if (StackExchange.settings.snippets.snippetsEnabled)
    StackExchange.using("snippets", function()
    createEditor();
    );

    else
    createEditor();

    );

    function createEditor()
    StackExchange.prepareEditor(
    heartbeatType: 'answer',
    autoActivateHeartbeat: false,
    convertImagesToLinks: false,
    noModals: true,
    showLowRepImageUploadWarning: true,
    reputationToPostImages: null,
    bindNavPrevention: true,
    postfix: "",
    imageUploader:
    brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
    contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/4.0/"u003ecc by-sa 4.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
    allowUrls: true
    ,
    onDemand: true,
    discardSelector: ".discard-answer"
    ,immediatelyShowMarkdownHelp:true
    );



    );














    draft saved

    draft discarded
















    StackExchange.ready(
    function ()
    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f250010%2fcan-default-object-names-be-changed%23new-answer', 'question_page');

    );

    Post as a guest















    Required, but never shown

























    2 Answers
    2






    active

    oldest

    votes








    2 Answers
    2






    active

    oldest

    votes









    active

    oldest

    votes






    active

    oldest

    votes









    2

















    What kind of parametrization/external programs could be used to
    achieve having such a name as default, when for example using a create
    table statements which mentions the fk but does not explicitly provide
    a constraint name?




    There's no way to change the default name generated when the DDL doesn't contain a name. The only thing you can do is to run a batch process to identify non-compliant objects and perhaps drop and recreate them.






    share|improve this answer





























      2

















      What kind of parametrization/external programs could be used to
      achieve having such a name as default, when for example using a create
      table statements which mentions the fk but does not explicitly provide
      a constraint name?




      There's no way to change the default name generated when the DDL doesn't contain a name. The only thing you can do is to run a batch process to identify non-compliant objects and perhaps drop and recreate them.






      share|improve this answer



























        2














        2










        2










        What kind of parametrization/external programs could be used to
        achieve having such a name as default, when for example using a create
        table statements which mentions the fk but does not explicitly provide
        a constraint name?




        There's no way to change the default name generated when the DDL doesn't contain a name. The only thing you can do is to run a batch process to identify non-compliant objects and perhaps drop and recreate them.






        share|improve this answer














        What kind of parametrization/external programs could be used to
        achieve having such a name as default, when for example using a create
        table statements which mentions the fk but does not explicitly provide
        a constraint name?




        There's no way to change the default name generated when the DDL doesn't contain a name. The only thing you can do is to run a batch process to identify non-compliant objects and perhaps drop and recreate them.







        share|improve this answer












        share|improve this answer



        share|improve this answer










        answered 8 hours ago









        David Browne - MicrosoftDavid Browne - Microsoft

        15.8k1 gold badge14 silver badges42 bronze badges




        15.8k1 gold badge14 silver badges42 bronze badges


























            2
















            If you want to discourage creation of auto-named constraints, you can do it using database-level DDL trigger for CREATE_TABLE and ALTER_TABLE events.



            Such as, for example



            CREATE TRIGGER [CheckConstraintsNaming] ON DATABASE
            FOR CREATE_TABLE, ALTER_TABLE
            AS
            BEGIN
            SET NOCOUNT ON;

            DECLARE @event xml, @e_type varchar(30), @s_name sysname, @o_name sysname, @o_id int, @is_filetable bit;
            SET @event = EVENTDATA();
            SET @e_type = @event.value('(/EVENT_INSTANCE/EventType/text())[1]', 'varchar(30)');
            SET @s_name = @event.value('(/EVENT_INSTANCE/SchemaName/text())[1]', 'sysname');
            SET @o_name = @event.value('(/EVENT_INSTANCE/ObjectName/text())[1]', 'sysname');
            SELECT @o_id = t.object_id, @is_filetable = t.is_filetable
            FROM sys.tables t
            JOIN sys.schemas s ON s.schema_id = t.schema_id
            WHERE s.name = @s_name AND t.name = @o_name;

            IF @is_filetable = 1
            RETURN;

            DECLARE @msgConstraints nvarchar(max), @msg nvarchar(max);

            SELECT
            @msgConstraints = STRING_AGG(QUOTENAME(c.name), CHAR(13) + CHAR(10))
            FROM (
            SELECT name FROM sys.key_constraints WHERE parent_object_id = @o_id AND is_system_named = 1
            UNION ALL
            SELECT name FROM sys.foreign_keys WHERE parent_object_id = @o_id AND is_system_named = 1
            UNION ALL
            SELECT name FROM sys.check_constraints WHERE parent_object_id = @o_id AND is_system_named = 1
            UNION ALL
            SELECT name FROM sys.default_constraints WHERE parent_object_id = @o_id AND is_system_named = 1
            ) c(name)
            WHERE @e_type = 'CREATE_TABLE'
            OR @e_type = 'ALTER_TABLE'
            AND @event.exist('/EVENT_INSTANCE/AlterTableActionList/Create/Constraints/Name[text()=sql:column("c.name")]') = 1;

            IF @msgConstraints IS NULL OR @msgConstraints = ''
            RETURN;

            SET @msg = 'Table ' + QUOTENAME(@s_name) + '.' + QUOTENAME(@o_name) + ' is being '
            + LOWER(LEFT(@e_type, 5)) + 'ed with one or more auto named constraints:'
            + CHAR(13) + CHAR(10) + @msgConstraints
            + CHAR(13) + CHAR(10) + 'Please specify constraint names explicitly.';

            THROW 51011, @msg, 1;
            ROLLBACK TRANSACTION;
            END
            GO


            Once you have it in database, things like



            CREATE TABLE TableName
            (
            id int NOT NULL,
            parent_id int NULL,
            name varchar(20) NOT NULL,
            dateCreated datetime NOT NULL DEFAULT (GETDATE()),
            value1 float NOT NULL,
            value2 tinyint NOT NULL,
            PRIMARY KEY (ID),
            FOREIGN KEY (parent_id) REFERENCES TableName,
            UNIQUE (name),
            CHECK ((value1 BETWEEN 0 AND 1) AND (value2 IN (1, 2, 4, 8)))
            );


            (and equivalent ALTER) will not be allowed.



            The error message thrown




            Msg 51011, Level 16, State 1, Procedure ConstraintNameCheck, Line 45
            [Batch Start Line 50]

            Table [dbo].[TableName] is being created with one or more auto named constraints:

            [PK__TableNam__3213E83FB1491772]

            [UQ__TableNam__72E12F1BE94335EB]

            [FK__TableName__paren__316D4A39]

            [CK__TableName__32616E72]

            [DF__TableName__dateC__30792600]

            Please specify constraint names explicitly.




            will remind you or your colleague to name constraints explicitly. It can be modified to suggest the "right" name additionally.




            Those who want to see it as a database option in future releases of SQL Server, such as



            ALTER DATABASE [DbName]
            SET CONSTRAINT_NAMING = EXPLICIT ;


            can cast a vote for my initiative here.






            share|improve this answer



























            • I like this, but as coded is disallows all CREATE TABLE and ALTER TABLE for any tables which already have system-named constraints.

              – David Browne - Microsoft
              6 hours ago











            • @DavidBrowne-Microsoft, hmm, I need to think if it can be addressed or not. But I must say that I never suffered from it, because of I usually normalize auto-named constraints (via batch process as you specified in your answer) and then trigger is added to guard against such things. It also has drawbacks if there is memory-optimized stuff in the database. I will try to amend answer later to include drawbacks explanation.

              – i-one
              5 hours ago











            • I'm not sure it needs to be changed. Just pointing that out.

              – David Browne - Microsoft
              4 hours ago















            2
















            If you want to discourage creation of auto-named constraints, you can do it using database-level DDL trigger for CREATE_TABLE and ALTER_TABLE events.



            Such as, for example



            CREATE TRIGGER [CheckConstraintsNaming] ON DATABASE
            FOR CREATE_TABLE, ALTER_TABLE
            AS
            BEGIN
            SET NOCOUNT ON;

            DECLARE @event xml, @e_type varchar(30), @s_name sysname, @o_name sysname, @o_id int, @is_filetable bit;
            SET @event = EVENTDATA();
            SET @e_type = @event.value('(/EVENT_INSTANCE/EventType/text())[1]', 'varchar(30)');
            SET @s_name = @event.value('(/EVENT_INSTANCE/SchemaName/text())[1]', 'sysname');
            SET @o_name = @event.value('(/EVENT_INSTANCE/ObjectName/text())[1]', 'sysname');
            SELECT @o_id = t.object_id, @is_filetable = t.is_filetable
            FROM sys.tables t
            JOIN sys.schemas s ON s.schema_id = t.schema_id
            WHERE s.name = @s_name AND t.name = @o_name;

            IF @is_filetable = 1
            RETURN;

            DECLARE @msgConstraints nvarchar(max), @msg nvarchar(max);

            SELECT
            @msgConstraints = STRING_AGG(QUOTENAME(c.name), CHAR(13) + CHAR(10))
            FROM (
            SELECT name FROM sys.key_constraints WHERE parent_object_id = @o_id AND is_system_named = 1
            UNION ALL
            SELECT name FROM sys.foreign_keys WHERE parent_object_id = @o_id AND is_system_named = 1
            UNION ALL
            SELECT name FROM sys.check_constraints WHERE parent_object_id = @o_id AND is_system_named = 1
            UNION ALL
            SELECT name FROM sys.default_constraints WHERE parent_object_id = @o_id AND is_system_named = 1
            ) c(name)
            WHERE @e_type = 'CREATE_TABLE'
            OR @e_type = 'ALTER_TABLE'
            AND @event.exist('/EVENT_INSTANCE/AlterTableActionList/Create/Constraints/Name[text()=sql:column("c.name")]') = 1;

            IF @msgConstraints IS NULL OR @msgConstraints = ''
            RETURN;

            SET @msg = 'Table ' + QUOTENAME(@s_name) + '.' + QUOTENAME(@o_name) + ' is being '
            + LOWER(LEFT(@e_type, 5)) + 'ed with one or more auto named constraints:'
            + CHAR(13) + CHAR(10) + @msgConstraints
            + CHAR(13) + CHAR(10) + 'Please specify constraint names explicitly.';

            THROW 51011, @msg, 1;
            ROLLBACK TRANSACTION;
            END
            GO


            Once you have it in database, things like



            CREATE TABLE TableName
            (
            id int NOT NULL,
            parent_id int NULL,
            name varchar(20) NOT NULL,
            dateCreated datetime NOT NULL DEFAULT (GETDATE()),
            value1 float NOT NULL,
            value2 tinyint NOT NULL,
            PRIMARY KEY (ID),
            FOREIGN KEY (parent_id) REFERENCES TableName,
            UNIQUE (name),
            CHECK ((value1 BETWEEN 0 AND 1) AND (value2 IN (1, 2, 4, 8)))
            );


            (and equivalent ALTER) will not be allowed.



            The error message thrown




            Msg 51011, Level 16, State 1, Procedure ConstraintNameCheck, Line 45
            [Batch Start Line 50]

            Table [dbo].[TableName] is being created with one or more auto named constraints:

            [PK__TableNam__3213E83FB1491772]

            [UQ__TableNam__72E12F1BE94335EB]

            [FK__TableName__paren__316D4A39]

            [CK__TableName__32616E72]

            [DF__TableName__dateC__30792600]

            Please specify constraint names explicitly.




            will remind you or your colleague to name constraints explicitly. It can be modified to suggest the "right" name additionally.




            Those who want to see it as a database option in future releases of SQL Server, such as



            ALTER DATABASE [DbName]
            SET CONSTRAINT_NAMING = EXPLICIT ;


            can cast a vote for my initiative here.






            share|improve this answer



























            • I like this, but as coded is disallows all CREATE TABLE and ALTER TABLE for any tables which already have system-named constraints.

              – David Browne - Microsoft
              6 hours ago











            • @DavidBrowne-Microsoft, hmm, I need to think if it can be addressed or not. But I must say that I never suffered from it, because of I usually normalize auto-named constraints (via batch process as you specified in your answer) and then trigger is added to guard against such things. It also has drawbacks if there is memory-optimized stuff in the database. I will try to amend answer later to include drawbacks explanation.

              – i-one
              5 hours ago











            • I'm not sure it needs to be changed. Just pointing that out.

              – David Browne - Microsoft
              4 hours ago













            2














            2










            2









            If you want to discourage creation of auto-named constraints, you can do it using database-level DDL trigger for CREATE_TABLE and ALTER_TABLE events.



            Such as, for example



            CREATE TRIGGER [CheckConstraintsNaming] ON DATABASE
            FOR CREATE_TABLE, ALTER_TABLE
            AS
            BEGIN
            SET NOCOUNT ON;

            DECLARE @event xml, @e_type varchar(30), @s_name sysname, @o_name sysname, @o_id int, @is_filetable bit;
            SET @event = EVENTDATA();
            SET @e_type = @event.value('(/EVENT_INSTANCE/EventType/text())[1]', 'varchar(30)');
            SET @s_name = @event.value('(/EVENT_INSTANCE/SchemaName/text())[1]', 'sysname');
            SET @o_name = @event.value('(/EVENT_INSTANCE/ObjectName/text())[1]', 'sysname');
            SELECT @o_id = t.object_id, @is_filetable = t.is_filetable
            FROM sys.tables t
            JOIN sys.schemas s ON s.schema_id = t.schema_id
            WHERE s.name = @s_name AND t.name = @o_name;

            IF @is_filetable = 1
            RETURN;

            DECLARE @msgConstraints nvarchar(max), @msg nvarchar(max);

            SELECT
            @msgConstraints = STRING_AGG(QUOTENAME(c.name), CHAR(13) + CHAR(10))
            FROM (
            SELECT name FROM sys.key_constraints WHERE parent_object_id = @o_id AND is_system_named = 1
            UNION ALL
            SELECT name FROM sys.foreign_keys WHERE parent_object_id = @o_id AND is_system_named = 1
            UNION ALL
            SELECT name FROM sys.check_constraints WHERE parent_object_id = @o_id AND is_system_named = 1
            UNION ALL
            SELECT name FROM sys.default_constraints WHERE parent_object_id = @o_id AND is_system_named = 1
            ) c(name)
            WHERE @e_type = 'CREATE_TABLE'
            OR @e_type = 'ALTER_TABLE'
            AND @event.exist('/EVENT_INSTANCE/AlterTableActionList/Create/Constraints/Name[text()=sql:column("c.name")]') = 1;

            IF @msgConstraints IS NULL OR @msgConstraints = ''
            RETURN;

            SET @msg = 'Table ' + QUOTENAME(@s_name) + '.' + QUOTENAME(@o_name) + ' is being '
            + LOWER(LEFT(@e_type, 5)) + 'ed with one or more auto named constraints:'
            + CHAR(13) + CHAR(10) + @msgConstraints
            + CHAR(13) + CHAR(10) + 'Please specify constraint names explicitly.';

            THROW 51011, @msg, 1;
            ROLLBACK TRANSACTION;
            END
            GO


            Once you have it in database, things like



            CREATE TABLE TableName
            (
            id int NOT NULL,
            parent_id int NULL,
            name varchar(20) NOT NULL,
            dateCreated datetime NOT NULL DEFAULT (GETDATE()),
            value1 float NOT NULL,
            value2 tinyint NOT NULL,
            PRIMARY KEY (ID),
            FOREIGN KEY (parent_id) REFERENCES TableName,
            UNIQUE (name),
            CHECK ((value1 BETWEEN 0 AND 1) AND (value2 IN (1, 2, 4, 8)))
            );


            (and equivalent ALTER) will not be allowed.



            The error message thrown




            Msg 51011, Level 16, State 1, Procedure ConstraintNameCheck, Line 45
            [Batch Start Line 50]

            Table [dbo].[TableName] is being created with one or more auto named constraints:

            [PK__TableNam__3213E83FB1491772]

            [UQ__TableNam__72E12F1BE94335EB]

            [FK__TableName__paren__316D4A39]

            [CK__TableName__32616E72]

            [DF__TableName__dateC__30792600]

            Please specify constraint names explicitly.




            will remind you or your colleague to name constraints explicitly. It can be modified to suggest the "right" name additionally.




            Those who want to see it as a database option in future releases of SQL Server, such as



            ALTER DATABASE [DbName]
            SET CONSTRAINT_NAMING = EXPLICIT ;


            can cast a vote for my initiative here.






            share|improve this answer















            If you want to discourage creation of auto-named constraints, you can do it using database-level DDL trigger for CREATE_TABLE and ALTER_TABLE events.



            Such as, for example



            CREATE TRIGGER [CheckConstraintsNaming] ON DATABASE
            FOR CREATE_TABLE, ALTER_TABLE
            AS
            BEGIN
            SET NOCOUNT ON;

            DECLARE @event xml, @e_type varchar(30), @s_name sysname, @o_name sysname, @o_id int, @is_filetable bit;
            SET @event = EVENTDATA();
            SET @e_type = @event.value('(/EVENT_INSTANCE/EventType/text())[1]', 'varchar(30)');
            SET @s_name = @event.value('(/EVENT_INSTANCE/SchemaName/text())[1]', 'sysname');
            SET @o_name = @event.value('(/EVENT_INSTANCE/ObjectName/text())[1]', 'sysname');
            SELECT @o_id = t.object_id, @is_filetable = t.is_filetable
            FROM sys.tables t
            JOIN sys.schemas s ON s.schema_id = t.schema_id
            WHERE s.name = @s_name AND t.name = @o_name;

            IF @is_filetable = 1
            RETURN;

            DECLARE @msgConstraints nvarchar(max), @msg nvarchar(max);

            SELECT
            @msgConstraints = STRING_AGG(QUOTENAME(c.name), CHAR(13) + CHAR(10))
            FROM (
            SELECT name FROM sys.key_constraints WHERE parent_object_id = @o_id AND is_system_named = 1
            UNION ALL
            SELECT name FROM sys.foreign_keys WHERE parent_object_id = @o_id AND is_system_named = 1
            UNION ALL
            SELECT name FROM sys.check_constraints WHERE parent_object_id = @o_id AND is_system_named = 1
            UNION ALL
            SELECT name FROM sys.default_constraints WHERE parent_object_id = @o_id AND is_system_named = 1
            ) c(name)
            WHERE @e_type = 'CREATE_TABLE'
            OR @e_type = 'ALTER_TABLE'
            AND @event.exist('/EVENT_INSTANCE/AlterTableActionList/Create/Constraints/Name[text()=sql:column("c.name")]') = 1;

            IF @msgConstraints IS NULL OR @msgConstraints = ''
            RETURN;

            SET @msg = 'Table ' + QUOTENAME(@s_name) + '.' + QUOTENAME(@o_name) + ' is being '
            + LOWER(LEFT(@e_type, 5)) + 'ed with one or more auto named constraints:'
            + CHAR(13) + CHAR(10) + @msgConstraints
            + CHAR(13) + CHAR(10) + 'Please specify constraint names explicitly.';

            THROW 51011, @msg, 1;
            ROLLBACK TRANSACTION;
            END
            GO


            Once you have it in database, things like



            CREATE TABLE TableName
            (
            id int NOT NULL,
            parent_id int NULL,
            name varchar(20) NOT NULL,
            dateCreated datetime NOT NULL DEFAULT (GETDATE()),
            value1 float NOT NULL,
            value2 tinyint NOT NULL,
            PRIMARY KEY (ID),
            FOREIGN KEY (parent_id) REFERENCES TableName,
            UNIQUE (name),
            CHECK ((value1 BETWEEN 0 AND 1) AND (value2 IN (1, 2, 4, 8)))
            );


            (and equivalent ALTER) will not be allowed.



            The error message thrown




            Msg 51011, Level 16, State 1, Procedure ConstraintNameCheck, Line 45
            [Batch Start Line 50]

            Table [dbo].[TableName] is being created with one or more auto named constraints:

            [PK__TableNam__3213E83FB1491772]

            [UQ__TableNam__72E12F1BE94335EB]

            [FK__TableName__paren__316D4A39]

            [CK__TableName__32616E72]

            [DF__TableName__dateC__30792600]

            Please specify constraint names explicitly.




            will remind you or your colleague to name constraints explicitly. It can be modified to suggest the "right" name additionally.




            Those who want to see it as a database option in future releases of SQL Server, such as



            ALTER DATABASE [DbName]
            SET CONSTRAINT_NAMING = EXPLICIT ;


            can cast a vote for my initiative here.







            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited 6 hours ago

























            answered 7 hours ago









            i-onei-one

            6194 silver badges12 bronze badges




            6194 silver badges12 bronze badges















            • I like this, but as coded is disallows all CREATE TABLE and ALTER TABLE for any tables which already have system-named constraints.

              – David Browne - Microsoft
              6 hours ago











            • @DavidBrowne-Microsoft, hmm, I need to think if it can be addressed or not. But I must say that I never suffered from it, because of I usually normalize auto-named constraints (via batch process as you specified in your answer) and then trigger is added to guard against such things. It also has drawbacks if there is memory-optimized stuff in the database. I will try to amend answer later to include drawbacks explanation.

              – i-one
              5 hours ago











            • I'm not sure it needs to be changed. Just pointing that out.

              – David Browne - Microsoft
              4 hours ago

















            • I like this, but as coded is disallows all CREATE TABLE and ALTER TABLE for any tables which already have system-named constraints.

              – David Browne - Microsoft
              6 hours ago











            • @DavidBrowne-Microsoft, hmm, I need to think if it can be addressed or not. But I must say that I never suffered from it, because of I usually normalize auto-named constraints (via batch process as you specified in your answer) and then trigger is added to guard against such things. It also has drawbacks if there is memory-optimized stuff in the database. I will try to amend answer later to include drawbacks explanation.

              – i-one
              5 hours ago











            • I'm not sure it needs to be changed. Just pointing that out.

              – David Browne - Microsoft
              4 hours ago
















            I like this, but as coded is disallows all CREATE TABLE and ALTER TABLE for any tables which already have system-named constraints.

            – David Browne - Microsoft
            6 hours ago





            I like this, but as coded is disallows all CREATE TABLE and ALTER TABLE for any tables which already have system-named constraints.

            – David Browne - Microsoft
            6 hours ago













            @DavidBrowne-Microsoft, hmm, I need to think if it can be addressed or not. But I must say that I never suffered from it, because of I usually normalize auto-named constraints (via batch process as you specified in your answer) and then trigger is added to guard against such things. It also has drawbacks if there is memory-optimized stuff in the database. I will try to amend answer later to include drawbacks explanation.

            – i-one
            5 hours ago





            @DavidBrowne-Microsoft, hmm, I need to think if it can be addressed or not. But I must say that I never suffered from it, because of I usually normalize auto-named constraints (via batch process as you specified in your answer) and then trigger is added to guard against such things. It also has drawbacks if there is memory-optimized stuff in the database. I will try to amend answer later to include drawbacks explanation.

            – i-one
            5 hours ago













            I'm not sure it needs to be changed. Just pointing that out.

            – David Browne - Microsoft
            4 hours ago





            I'm not sure it needs to be changed. Just pointing that out.

            – David Browne - Microsoft
            4 hours ago


















            draft saved

            draft discarded















































            Thanks for contributing an answer to Database Administrators Stack Exchange!


            • Please be sure to answer the question. Provide details and share your research!

            But avoid


            • Asking for help, clarification, or responding to other answers.

            • Making statements based on opinion; back them up with references or personal experience.

            To learn more, see our tips on writing great answers.




            draft saved


            draft discarded














            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fdba.stackexchange.com%2fquestions%2f250010%2fcan-default-object-names-be-changed%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown





















































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown

































            Required, but never shown














            Required, but never shown












            Required, but never shown







            Required, but never shown







            Popular posts from this blog

            Canceling a color specificationRandomly assigning color to Graphics3D objects?Default color for Filling in Mathematica 9Coloring specific elements of sets with a prime modified order in an array plotHow to pick a color differing significantly from the colors already in a given color list?Detection of the text colorColor numbers based on their valueCan color schemes for use with ColorData include opacity specification?My dynamic color schemes

            Invision Community Contents History See also References External links Navigation menuProprietaryinvisioncommunity.comIPS Community ForumsIPS Community Forumsthis blog entry"License Changes, IP.Board 3.4, and the Future""Interview -- Matt Mecham of Ibforums""CEO Invision Power Board, Matt Mecham Is a Liar, Thief!"IPB License Explanation 1.3, 1.3.1, 2.0, and 2.1ArchivedSecurity Fixes, Updates And Enhancements For IPB 1.3.1Archived"New Demo Accounts - Invision Power Services"the original"New Default Skin"the original"Invision Power Board 3.0.0 and Applications Released"the original"Archived copy"the original"Perpetual licenses being done away with""Release Notes - Invision Power Services""Introducing: IPS Community Suite 4!"Invision Community Release Notes

            François Viète Contents Biography Work and thought Bibliography See also Notes Further reading External links Navigation menup. 21Google Bookspp. 75–77Google BooksDe thou (from University of Saint Andrews)ArchivedGoogle BooksGoogle BooksGoogle BooksGoogle booksGoogle Bookscc-parthenay.frL'histoire universelle (fr)Universal History (en)ArchivedAdsabs.harvard.eduPagesperso-orange.frArchive.orgChikara Sasaki. Descartes' mathematical thought p.259Google BooksGoogle BooksGoogle Bookspp. 152 and onwardGoogle BooksGoogle BooksScribd.comGoogle Books1257-7979Google BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGoogle BooksGallica.bnf.frGoogle BooksGoogle Books"François Viète"Francois Viète: Father of Modern Algebraic NotationThe Lawyer and the GamblerAbout TarporleySite de Jean-Paul GuichardL'algèbre nouvelle"About the Harmonicon"cb120511976(data)1188044800000 0001 0913 5903n82164680ola2013766880073431702w6vt1sb70287374827140948071409480