[英]How do you enforce unique across 2 tables in SQL Server
要求 :
实现方式 :
Create Table EmpFT( EPID int primary key, F1, F2, etc)
Create Table EmpPT( EPID int primary key, P1, P2, etc)
--This does not prevent same EPID on both EmpFT and EmpPT.
您如何在数据库中实现3号?
我正在使用SQL Server 2012标准版。
试试这个方法:
CREATE TABLE Emp(EPID INT PRIMARY KEY,
t CHAR(2) NOT NULL, UNIQUE (EPID,t));
CREATE TABLE EmpFT(EPID INT PRIMARY KEY, ... other columns
t CHAR(2) NOT NULL CHECK (t = 'FT'),
FOREIGN KEY (EPID,t) REFERENCES Emp (EPID,t));
CREATE TABLE EmpPT(EPID INT PRIMARY KEY, ... other columns
t CHAR(2) NOT NULL CHECK (t = 'PT'),
FOREIGN KEY (EPID,t) REFERENCES Emp (EPID,t));
您可以添加检查约束。 两个表都这样
ALTER TABLE EmpFT
ADD CONSTRAINT chk_EmpFT_EPID CHECK (dbo.CHECK_EmpPT(EPID)= 0)
ALTER TABLE EmpPT
ADD CONSTRAINT chk_EmpPT_EPID CHECK (dbo.CHECK_EmpFT(EPID)= 0)
像这样的功能:
CREATE FUNCTION CHECK_EmpFT(@EPID int)
RETURNS int
AS
BEGIN
DECLARE @ret int;
SELECT @ret = count(*) FROM EmpFT WHERE @EPID = EmpFT.EPID
RETURN @ret;
END
GO
CREATE FUNCTION CHECK_EmpPT(@EPID int)
RETURNS int
AS
BEGIN
DECLARE @ret int;
SELECT @ret = count(*) FROM EmpPT WHERE @EPID = EmpPT.EPID
RETURN @ret;
END
GO
在这里进一步阅读:
您可以为所有员工创建一个合并表。 FT和PT表可以使用到employee表的外键。
您不能具有主键跨度表。 因此,一种方法是创建具有适当约束的表employee
。 可能看起来像这样:
create table employee (
EPID int not null identity(1, 1) primary key,
FTID int references empft(empftid),
PTID int references emppt(empptid),
CHECK (FTID is not null and PTID is null or FTID is null and PTID is not null),
UNIQUE (FTID),
UNIQUE (PTID)
. . .
);
create table empft (
EmpFTId int not null identity(1, 1) primary key,
. . .
);
create table emppt (
EmpPTId int not null identity(1, 1) primary key,
. . .
);
当然,您也可以根据需要使用触发器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.