SQL引用多个表

时间:2014-04-01 06:55:32

标签: sql multiple-tables referential-integrity

我想在SQL中定义一个映射。映射是从一个源表到几个目标表。我使用参照完整性,因此如果删除源表中的值,则也应删除映射表中的值。表格的定义看起来应该是这样的:

-- Table with source members
Create Table dbo.Source_Members
(
    Id int IDENTITY(1,1) Not Null,
    Name [nvarchar](50) Null
    CONSTRAINT [PK_Source_Members_Id] PRIMARY KEY CLUSTERED
    (
        Id
    )
);
-- Table with target members
Create Table dbo.Target_Members1
(
    Id int IDENTITY(1,1) Not Null,
    Name [nvarchar](50) Null,
    Target_Table_Id int DEFAULT 1
    CONSTRAINT [PK_Target_Members1_Id] PRIMARY KEY CLUSTERED
    (
        Id, Target_Table_Id
    )
);
Create Table dbo.Target_Members2
(
    Id int IDENTITY(1,1) Not Null,
    Name [nvarchar](50) Null,
    Target_Table_Id int DEFAULT 2
    CONSTRAINT [PK_Target_Members2_Id] PRIMARY KEY CLUSTERED
    (
        Id, Target_Table_Id
    )
);
-- Mapping table
Create Table dbo.Mapping
(
    Id int IDENTITY(1,1) Not Null,
    Id_Source_Members int Not Null,
    Id_Target_Members int Not Null,
    Target_Table_Id int Not Null
    CONSTRAINT [PK_Mapping] PRIMARY KEY CLUSTERED
    (
        Id
    )
);
-- Define first Foreign Key, referencing the source member (just one table)
Alter Table dbo.Mapping WITH CHECK
ADD CONSTRAINT [FK_Source_Members] FOREIGN KEY (Id_Source_Members) REFERENCES dbo.Source_Members (Id)
ON UPDATE CASCADE
ON DELETE CASCADE
-- Define second Foreign Key, referencing the target member (several tables)
Alter Table dbo.Mapping WITH CHECK
ADD CONSTRAINT [FK_Target_Members1] FOREIGN KEY (Id_Target_Members, Target_Table_Id) REFERENCES dbo.Target_Members1 (Id, Target_Table_Id)
ON UPDATE CASCADE
ON DELETE CASCADE
Alter Table dbo.Mapping WITH CHECK
ADD CONSTRAINT [FK_Target_Members2] FOREIGN KEY (Id_Target_Members, Target_Table_Id) REFERENCES dbo.Target_Members2 (Id, Target_Table_Id)
ON UPDATE CASCADE
ON DELETE CASCADE

但这种定义不起作用。我想在映射表中插入值,如:

INSERT INTO dbo.Mapping(Id_Source_Members, Id_Target_Members, Target_Table_Id)
SELECT 1, 1, 1
UNION
SELECT 2, 1, 2
UNION
SELECT 3, 2, 2

与此类似,第一个源值应映射到Target_Members1中的第一个值。第二个源值应映射到Target_Members2中的第一个值。第三个源值应映射到Target_Members2中的第二个值,依此类推。正如我之前提到的,它并没有像那样工作。我怎么做那样的事情,失败在哪里?

1 个答案:

答案 0 :(得分:0)

您无法一次插入多个表格。您需要单独的SQL语句来执行此操作。

所以你需要:

INSERT INTO Source_Members(Name)
SELECT 'x'
UNION
SELECT 'y'
UNION
SELECT 'z'
;

INSERT INTO Target_Members1(Target_Table_Id)
SELECT 1
UNION
SELECT 2
;

INSERT INTO Target_Members2(Target_Table_Id)
SELECT 1
UNION
SELECT 2
;

INSERT INTO Mapping(Id_Source_Members, Id_Target_Members, Target_Table_Id)
SELECT 1, 1, 1
UNION
SELECT 3, 2, 2
;