I am facing a problem in SQL Server with copying multiple related tables at a time.
I have two tables. One is StageDetails
and another is StageDetailsItem
.
The StageDetails
table contains three rows and the StageDetailsItem
table contains fifteen rows.
Each row from StageDetails
has five rows in StageDetailsItem
.
There is a master-details relationship between StateDetails
and StageDetailsItems
.
I want to copy three StageDetails
records and fifteen StageDetailsItem
records in one shot
into the same tables and I want to change StageDetailID
of StageDetailsItem
when StageDetailsItem
is being inserted.
I don't want to use an explicit loop, like CURSOR
, WHILE
, etc.
Here is the DDL script for StageDetails
and StageDetailsItem
.
CREATE TABLE [dbo].[StageDetail](
[StageDetailID] [int] IDENTITY(1,1) NOT NULL,
[StageNUmber] [nvarchar](50) NULL,
[TypeOfStage] [nvarchar](500) NULL,
[Distance] [nvarchar](500) NULL,
CONSTRAINT [PK_StageDetail] PRIMARY KEY CLUSTERED
(
[StageDetailID] 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
CREATE TABLE [dbo].[StageDetailItem](
[StageDetailItemID] [int] IDENTITY(1,1) NOT NULL,
[StageDetailID] [int] NULL,
[Road] [nvarchar](500) NULL,
[CostPer] [nvarchar](500) NULL,
CONSTRAINT [PK_StageDetailItem] PRIMARY KEY CLUSTERED
(
[StageDetailItemID] 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].[StageDetailItem] WITH CHECK
ADD CONSTRAINT [FK_StageDetailItem_StageDetail] FOREIGN KEY([StageDetailID])
REFERENCES [dbo].[StageDetail] ([StageDetailID])
GO
ALTER TABLE [dbo].[StageDetailItem]
CHECK CONSTRAINT [FK_StageDetailItem_StageDetail]
GO
I can easily copy records from one table like this:
INSERT INTO EventDetailsEventType(EventID, EventTypeID)
SELECT @EventDetailsID, EventTypeID
FROM EventDetailsEventType
WHERE EventID = @ParentEventID;