级联从SQL中的多个表中删除行

时间:2014-05-26 14:13:02

标签: sql sql-server cascading-deletes

我有两张具有以下结构的表格:

  • 编号
  • 名称

  • 编号
  • PERSONID
  • 序列

和一些数据:

1   name1
2   name2
3   name3

1   1   3
2   1   1
3   1   2
4   2   1

Class表可以包含与Person中的一行相关的多行。来自PersonId表的ClassId表中Person的外键。我想删除与Person相关的Id数据,因此请使用一个查询从Class中删除3行,从Person删除1行。

我如何在SQL中执行此操作?

1 个答案:

答案 0 :(得分:0)

试试这个:

CREATE TABLE [dbo].[Class](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [PersonId] [int] NULL,
    [Sequence] [int] NULL,
 CONSTRAINT [PK_Class] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
/****** Object:  Table [dbo].[Person]    Script Date: 26-05-2014 07:54:26 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[Person](
    [Id] [int] IDENTITY(1,1) NOT NULL,
    [Person] [nchar](10) NULL,
 CONSTRAINT [PK_Person] PRIMARY KEY CLUSTERED 
(
    [Id] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
) ON [PRIMARY]

GO
ALTER TABLE [dbo].[Class]  WITH CHECK ADD  CONSTRAINT [FK_Class_Person] FOREIGN KEY([PersonId])
REFERENCES [dbo].[Person] ([Id])
ON DELETE CASCADE
GO
ALTER TABLE [dbo].[Class] CHECK CONSTRAINT [FK_Class_Person]
GO