数据库中可以有同名的约束吗? [英] Can there be constraints with the same name in a DB?

查看:179
本文介绍了数据库中可以有同名的约束吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我在此处提出的问题中的一个后续问题。

This is a follow-on question from the one I asked here.

数据库中的约束可以使用相同的名称吗?

Can constraints in a DB have the same name?

说我有:

CREATE TABLE Employer
(
    EmployerCode    VARCHAR(20)    PRIMARY KEY,
    Address         VARCHAR(100)   NULL
)


CREATE TABLE Employee
(
    EmployeeID      INT            PRIMARY KEY,
    EmployerCode    VARCHAR(20)    NOT NULL,
    CONSTRAINT employer_code_fk FOREIGN KEY (EmployerCode) REFERENCES Employer
)


CREATE TABLE BankAccount
(
    BankAccountID   INT            PRIMARY KEY,
    EmployerCode    VARCHAR(20)    NOT NULL,
    Amount          MONEY          NOT NULL,
    CONSTRAINT employer_code_fk FOREIGN KEY (EmployerCode) REFERENCES Employer
)

是这个允许吗?是否取决于DBMS(我使用的是SQL Server 2005)?如果不允许,那么是否有人对如何解决它有任何建议?

Is this allowable? Does it depend on the DBMS (I'm on SQL Server 2005)? If it is not allowable, does anyone have any suggestions on how to work around it?

推荐答案

否-约束是数据库

尝试添加例如

CREATE TABLE BankAccount
(
    BankAccountID   INT            PRIMARY KEY,
    EmployerCode    VARCHAR(20)    NOT NULL,
    Amount          MONEY          NOT NULL,
    CONSTRAINT FK_BankAccount_Employer 
        FOREIGN KEY (EmployerCode) REFERENCES Employer
)

我们基本上使用 FK _(子表)_(父表)来命名约束,并且

We basically use "FK_"(child table)_(parent table)" to name the constraints and are quite happy with this naming convention.

来自MSDN的信息

该约束名称必须对模式唯一(即,同一数据库中的两个不同模式都可以包含具有相同名称的约束)没有明确记录,而是需要假设数据库对象的标识符在所包含的模式内必须唯一。 em>除非另行指定,所以约束名称为定义为:

That constraint names have to be unique to the schema (ie. two different schemas in the same database can both contain a constraint with the same name) is not explicitly documented. Rather you need to assume the identifiers of database objects must be unique within the containing schema unless specified otherwise. So the constraint name is defined as:


约束的名称。约束名称必须遵循标识符规则,但名称不能以数字符号(#)开头。如果未提供constraint_name,则会将系统生成的名称分配给该约束。

Is the name of the constraint. Constraint names must follow the rules for identifiers, except that the name cannot start with a number sign (#). If constraint_name is not supplied, a system-generated name is assigned to the constraint.

将其与索引


是索引的名称。索引名称在表或视图中必须唯一,但在数据库中不必唯一。索引名称必须遵循标识符规则。

Is the name of the index. Index names must be unique within a table or view but do not have to be unique within a database. Index names must follow the rules of identifiers.

这明显缩小了标识符的范围。

which explicitly narrows the scope of the identifier.

这篇关于数据库中可以有同名的约束吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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