我有两张具有以下结构的表格:
人
类
和一些数据:
人
1 name1
2 name2
3 name3
类
1 1 3
2 1 1
3 1 2
4 2 1
Class
表可以包含与Person
中的一行相关的多行。来自PersonId
表的Class
是Id
表中Person
的外键。我想删除与Person
相关的Id
数据,因此请使用一个查询从Class
中删除3行,从Person
删除1行。
我如何在SQL中执行此操作?
答案 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