多个表上的SQL检查约束

时间:2017-01-25 16:29:13

标签: sql sql-server

因此,如果“类型”为0,我应该能够在表B中添加我的人,否则不能,但“类型”列不是也不应该在表B中。 enter image description here

2 个答案:

答案 0 :(得分:0)

你可以使用外键约束和一些技巧来做到这一点。

首先,为TableAtype 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

enter image description here

 --Clean up
    DROP TABLE T2;
    DROP TABLE T1;
    GO