我正在尝试编写一个删除相关记录的存储过程。如果您查看下面的图像,您将看到展位如何具有展位类型和展厅,展位类型具有productid
,然后将其包含在产品表中。
基本上,我试图删除一个大厅,这意味着还要删除展位,展位类型和展位类型的产品。
我甚至不知道从哪里开始,因为我对sql很新,所以任何指导或链接都会受到赞赏。
答案 0 :(得分:2)
如果您在表DDL上设置了删除设置级别,那么如果您在父表上删除,则删除将级联到子表及其子项递归。
更多信息:http://www.techonthenet.com/sql_server/foreign_keys/foreign_delete.php
要从每个表中进行manaully删除,您需要从最少的表中删除,从子项删除到父项,使用联接来帮助。
答案 1 :(得分:0)
所以我最终按照@TheMadDBA的建议使用了连接和DELETE FROM,以便为他/她提供这个想法。最开始依赖于最依赖的
USE [DB]
GO
/****** Object: StoredProcedure [Exhibit].[DeleteHallAndRelatedData] Script Date: 7/7/2015 2:30:42 PM ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
---------------------- DeleteHallAndRelatedData ----------------------------------------------------------------------------
ALTER PROC [Exhibit].[DeleteHallAndRelatedData]
@OwnerId UniqueIdentifier,
@HallId UniqueIdentifier
AS
-----------------------------------------------------------------------------------------------------
SET NOCOUNT ON
Print N'DELETING PRICE SPLITS'
delete spl from
Shopping.PriceSplit spl
join Shopping.Price prc on prc.id=spl.priceId
join Shopping.Product prd on prd.Id = prc.ProductId
join Exhibit.BoothType bt on bt.BoothTypeProductId=prd.Id
Join Exhibit.Booth b on b.BoothTypeId=bt.BoothTypeProductId
where
b.HallId= @HallId and b.OwnerId = @OwnerId
Print N'DELETING PRICES'
delete prc from
Shopping.Price prc
join Shopping.Product prd on prd.Id = prc.ProductId
join Exhibit.BoothType bt on bt.BoothTypeProductId=prd.Id
Join Exhibit.Booth b on b.BoothTypeId=bt.BoothTypeProductId
where
b.HallId= @HallId and b.OwnerId = @OwnerId
Print N'DELETING PRODUCTS'
delete prd from
Shopping.Product prd
join Exhibit.BoothType bt on bt.BoothTypeProductId=prd.Id
Join Exhibit.Booth b on b.BoothTypeId=bt.BoothTypeProductId
where
b.HallId= @HallId and b.OwnerId = @OwnerId
Print N'DELETING BOOTH TYPES'
delete bt from
Exhibit.BoothType bt
Join Exhibit.Booth b on b.BoothTypeId=bt.BoothTypeProductId
where
b.HallId= @HallId and b.OwnerId = @OwnerId
Print N'DELETING BOOTHS'
delete from Exhibit.Booth where HallId = @HallId
Print N'DELETING HALL'
delete from Exhibit.Hall where Id = @HallId