Pour dupliquer un parents et beaucoup d'enfants avec des identités comme les clés, je pense que la clause OUTPUT
peut rendre les choses assez propre (SqlFiddle here):
-- Make a duplicate of parent 1, including children
-- Setup some test data
create table Parents (
ID int not null primary key identity
, Col1 varchar(10) not null
, Col2 varchar(10) not null
)
insert into Parents (Col1, Col2) select 'A', 'B'
insert into Parents (Col1, Col2) select 'C', 'D'
insert into Parents (Col1, Col2) select 'E', 'F'
create table Children (
ID int not null primary key identity
, ParentID int not null references Parents (ID)
, Col1 varchar(10) not null
, Col2 varchar(10) not null
)
insert into Children (ParentID, Col1, Col2) select 1, 'g', 'h'
insert into Children (ParentID, Col1, Col2) select 1, 'i', 'j'
insert into Children (ParentID, Col1, Col2) select 2, 'k', 'l'
insert into Children (ParentID, Col1, Col2) select 3, 'm', 'n'
-- Get one parent to copy
declare @oldID int = 1
-- Create a place to store new ParentID
declare @newID table (
ID int not null primary key
)
-- Create new parent
insert into Parents (Col1, Col2)
output inserted.ID into @newID -- Capturing the new ParentID
select Col1, Col2
from Parents
where ID = @oldID -- Only one parent
-- Create new children using the new ParentID
insert into Children (ParentID, Col1, Col2)
select n.ID, c.Col1, c.Col2
from Children c
cross join @newID n
where c.ParentID = @oldID -- Only one parent
-- Show some output
select * from Parents
select * from Children
vous pouvez utiliser la table temporaire et stocker proc fais le problème. – Hiten004
Quelle version de SQL Server/Sybase? –
Le OrderName est-il unique par client? Donc, un client a-t-il déjà plusieurs commandes avec le même OrderName? – Jacco