答案 0 :(得分:0)
你可以使用外键约束和一些技巧来做到这一点。
首先,为TableA
和type
person
设置一个唯一约束:
alter table TableA add constraint unq_TableA_type_person on TableA(type, person);
这允许您设置设置外键约束。但是,您需要type
列。为此,您可以使用计算列:
alter table TableB add type_for_a as (0); -- it is always 0
现在,只需使用外键约束:
alter table TableB add constraint fk_tableA_type_person
foreign key (type_for_a, person) references tableA(type, person);
瞧!您有约束,无需编写任何代码。
答案 1 :(得分:0)
CREATE TABLE T1 (TypeID INT NOT NULL, people VARCHAR(50));
GO
CREATE TABLE T2 ( people VARCHAR(50));
GO
-- creating trigger to insert on the behalf when there is a particular type
CREATE TRIGGER dbo.AfterInsertTrigger
ON T1
AFTER INSERT
AS
BEGIN
SET NOCOUNT ON;
declare @id int,
@someval char(1)
insert into dbo.T2
select i.people FROM Inserted i
where i.TypeID=0 -- checks only when the id is 0
END
GO
-- inserting people with different id s into Table1
INSERT T1 (TypeID, people) SELECT 1, 'A';
INSERT T1 (TypeID, people) SELECT 0, 'B';
GO
--selecting from tables see what got affected.
select * from T1
select *from T2
--Clean up
DROP TABLE T2;
DROP TABLE T1;
GO