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;
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
add a comment
|
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
1
I think what you are wanting is policy based management. This isn't an external program though.
– scsimon
8 hours ago
add a comment
|
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
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
sql-server
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
add a comment
|
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
add a comment
|
2 Answers
2
active
oldest
votes
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.
add a comment
|
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.
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
add a comment
|
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
);
);
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
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.
add a comment
|
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.
add a comment
|
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.
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.
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
add a comment
|
add a comment
|
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.
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
add a comment
|
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.
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
add a comment
|
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.
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.
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
add a comment
|
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
add a comment
|
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.
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
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
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Required, but never shown
Sign up or log in
StackExchange.ready(function ()
StackExchange.helpers.onClickDraftSave('#login-link');
);
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
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
1
I think what you are wanting is policy based management. This isn't an external program though.
– scsimon
8 hours ago