约束命名的目的是什么? [英] What is the purpose of constraint naming

查看:517
本文介绍了约束命名的目的是什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

命名您的约束(唯一,主键,外键)的目的是什么?



说我有一个表使用自然键作为主键:

  CREATE TABLE Order 

LoginName VARCHAR(50)NOT NULL,
ProductName VARCHAR(50)NOT NULL,
NumberOrdered INT NOT NULL,
OrderDateTime DATETIME NOT NULL,
PRIMARY KEY(LoginName,OrderDateTime)
);

命名我的PK带来什么好处(如果有)?



例如。
替换:

  PRIMARY KEY(LoginName,OrderDateTime)
pre>

使用:

  CONSTRAINT Order_PK PRIMARY KEY(LoginName,OrderDateTime )

对不起,如果我的数据模型不是最好的,我是新的! >

解决方案

这里有一些很基本的原因。



插入,更新,删除)违反约束,SQL将生成一个错误消息,其中将包含约束名称。如果约束名称是清楚和描述性的,错误消息将更容易理解;如果约束名称是一个随机的基于guid的名称,它是很少不清楚。对于最终用户来说,这是特别的,谁会(确定,可能)给你打电话,问 FK__B__B_COL1__75435199 是什么意思。



(2)如果约束需要在将来被修改(是的,它发生),如果你不知道它的命名是很难做。 (ALTER TABLE MyTable drop CONSTRAINT um ...)如果您从头开始创建多个数据库实例,并使用系统生成的默认名称,则不会有两个名称匹配。



(3)如果支持你的代码(也就是DBA)的人在星期日凌晨3点要浪费很多无意义的时间处理case(1)或case(2)很可能能够识别代码来自哪里,并能够做出相应的反应。


What is the purpose of naming your constraints (unique, primary key, foreign key)?

Say I have a table which is using natural keys as a primary key:

CREATE TABLE Order
(
    LoginName        VARCHAR(50)    NOT NULL,
    ProductName      VARCHAR(50)    NOT NULL,
    NumberOrdered    INT            NOT NULL,
    OrderDateTime    DATETIME       NOT NULL,
    PRIMARY KEY(LoginName, OrderDateTime)
);

What benefits (if any) does naming my PK bring?

Eg. Replace:

    PRIMARY KEY(LoginName, OrderDateTime)

With:

    CONSTRAINT Order_PK PRIMARY KEY(LoginName, OrderDateTime)

Sorry if my data model is not the best, I'm new to this!

解决方案

Here's some pretty basic reasons.

(1) If a query (insert, update, delete) violates a constraint, SQL will generate an error message that will contain the constraint name. If the constraint name is clear and descriptive, the error message will be easier to understand; if the constraint name is a random guid-based name, it's a lot less clear. Particulary for end-users, who will (ok, might) phone you up and ask what "FK__B__B_COL1__75435199" means.

(2) If a constraint needs to be modified in the future (yes, it happens), it's very hard to do if you don't know what it's named. (ALTER TABLE MyTable drop CONSTRAINT um...) And if you create more than one instance of the database "from scratch" and use system-generated default names, no two names will ever match.

(3) If the person who gets to support your code (aka a DBA) has to waste a lot of pointless time dealing with case (1) or case (2) at 3am on Sunday, they're quite probably in a position to identify where the code came from and be able to react accordingly.

这篇关于约束命名的目的是什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆