sql server programming:
The cascaded delete is easier to manage and involves no code:
ALTER TABLE [dbo].[Books] ADD
CONSTRAINT [FK_Books_Authors] FOREIGN KEY
(
[AuthorID]
) REFERENCES [dbo].[Authors] (
[AuthorID]
ON DELETE CASCADE
)
--
Tom
----------------------------------------------------
Thomas A. Moreau, BSc, PhD, MCSE, MCDBA
SQL Server MVP
Columnist, SQL Server Professional
Toronto, ON Canada
www.pinpub.com ..
[quoted text, click to view] "matthias s." <postamt[theat]emvoid[thedot]de> wrote in message
news:u2$lv%23nfFHA.272@TK2MSFTNGP15.phx.gbl...
Hi there,
for testing purposes I've created two tables, Authors and Books (table defs
at the end of the message). I have a one to many relationship between them
(1 Author can have n Books).
My question is: how do I delete an Author from the table? Do I have to start
a transaction, remove the books (of this author), then the author and
commit? Is there a better way? Shall I set it up altogether different (I've
seen the Cascading delete option, but I'm not really sure whether to use it
or not)?
Would be great if somebody could shed some light.
Thanks in advance.
/matthias
--Authors Table
CREATE TABLE [dbo].[Authors] (
[AuthorID] [int] IDENTITY (1, 1) NOT NULL ,
[FirstName] [varchar] (50) NOT NULL ,
[LastName] [varchar] (50) NOT NULL
) ON [PRIMARY]
ALTER TABLE [dbo].[Authors] WITH NOCHECK ADD
CONSTRAINT [PK_Authors] PRIMARY KEY CLUSTERED
(
[AuthorID]
) ON [PRIMARY]
--Books Table
CREATE TABLE [dbo].[Books] (
[BookID] [int] IDENTITY (1, 1) NOT NULL ,
[Title] [varchar] (50) NOT NULL ,
[AuthorID] [int] NOT NULL
) ON [PRIMARY]
ALTER TABLE [dbo].[Books] WITH NOCHECK ADD
CONSTRAINT [PK_Books] PRIMARY KEY CLUSTERED
(
[BookID]
) ON [PRIMARY]
-- Relationship
ALTER TABLE [dbo].[Books] ADD
CONSTRAINT [FK_Books_Authors] FOREIGN KEY
(
[AuthorID]
) REFERENCES [dbo].[Authors] (
[AuthorID]
)