sql - Deleting rows without CASCADE DELETE? -
i have database in sql server, have 1 table customers, , each customer can have multiple bookings, booking can belong 1 customer. point have written api , client side app using wpf, noticed cannot delete customer without deleting associated bookings customer. t-sql looks roughly:
set ansi_nulls on go set quoted_identifier on go create table [dbo].[customer]( [id] [int] identity(1,1) not null, [fullname] [nvarchar](50) not null, [dateofbirth] [date] not null, [phone] [nvarchar](20) not null, primary key clustered ( [id] asc )) set ansi_nulls on go set quoted_identifier on go create table [dbo].[booking]( [id] [int] identity(1,1) not null, [amount] [decimal](10,2) not null, [customerid] [int] not null, primary key clustered ( [id] asc )) alter table [dbo].booking check add constraint [fk_booking_customer] foreign key([customerid]) references [dbo].[customer] ([id]) go alter table [dbo].[booking] check constraint [fk_booking_customer] go
then, have delete stored procedure defined this:
create procedure deletecustomer @id int begin set nocount on; delete [dbo].[customer] id = @id end go
but said cannot delete customer has existing bookings. 1 way surely use cascade delete, don't want bookings deleted if customer deleted. idea how overcome problem or workarounds?
the options see are:
- make foreign key column
[customerid]
nullable, , useon delete set null
- use soft delete on
customer
table, e.g. bit column suchisactive
orisdeleted
. - disable foreign key:
alter table [dbo].booking nocheck constraint [fk_booking_customer]
- drop foreign key.
in situations implement soft delete option.
Comments
Post a Comment