这是我提出的问题 here 的后续问题.
数据库中的约束可以具有相同的名称吗?
假设我有:
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)?如果不允许,有人对如何解决它有任何建议吗?
最佳答案
不 - 约束也是一个数据库对象,因此它的名称必须是唯一的。
尝试添加例如将表名称添加到您的约束中,这样它将是唯一的。
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_”(子表)_(父表)”来命名约束,并且对这种命名约定非常满意。
信息来自 MSDN
没有明确记录约束名称对于模式必须是唯一的(即同一数据库中的两个不同模式可以都包含具有相同名称的约束)。相反,您需要假设数据库对象的标识符在包含模式中必须是唯一的除非另有指定。所以约束名称是 defined如:
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.
将其与 index 的名称进行比较:
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.
这显式缩小了标识符的范围。
关于sql - 数据库中可以存在同名约束吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1397671/