sql >> Database teknologi >  >> RDS >> Sqlserver

Hvordan kopierer man tabeller og undgår markører i SQL?

Du kan bruge output-sætningen med merge-sætningen for at få en mapping mellem kilde-id og mål-id. Beskrevet i dette spørgsmål. Brug af merge..output for at få kortlægning mellem source.id og target.id

Her er noget kode, som du kan teste. Jeg bruger tabelvariable i stedet for rigtige tabeller.

Opsætning af eksempeldata:

-- @A and @B is the source tables declare @A as table ( id int, FK_A_B int, name varchar(10) ) declare @B as table ( id int, visible bit ) -- Sample data in @A and @B insert into @B values (21, 1),(32, 0) insert into @A values (1, 21, 'n1'),(5, 32, 'n2') -- @C and @D is the target tables with id as identity columns declare @C as table ( id int identity, FK_C_D int not null, name varchar(10) ) declare @D as table ( id int identity, visible bit ) -- Sample data already in @C and @D insert into @D values (1),(0) insert into @C values (1, 'x1'),(1, 'x2'),(2, 'x3')

Kopier data:

-- The @IdMap is a table that holds the mapping between
-- the @B.id and @D.id (@D.id is an identity column)
declare @IdMap table(TargetID int, SourceID int)

-- Merge from @B to @D.
merge @D as D             -- Target table
using @B as B             -- Source table
on 0=1                    -- 0=1 means that there are no matches for merge
when not matched then
  insert (visible) values(visible)    -- Insert to @D
output inserted.id, B.id into @IdMap; -- Capture the newly created inserted.id and
                                      -- map that to the source (@B.id)

-- Add rows to @C from @A with a join to
-- @IdMap to get the new id for the FK relation
insert into @C(FK_C_D, name)
select I.TargetID, A.name 
from @A as A
  inner join @IdMap as I
    on A.FK_A_B = I.SourceID
 

Resultat:

select *
from @D as D
  inner join @C as C
    on D.id = C.FK_C_D

id          visible id          FK_C_D      name
----------- ------- ----------- ----------- ----------
1           1       1           1           x1
1           1       2           1           x2
2           0       3           2           x3
3           1       4           3           n1
4           0       5           4           n2
 

Du kan teste koden her:https://data.stackexchange.com/stackoverflow/q/101643/using-merge-to-map-source-id-to-target-id



  1. OpenShift webapps mysql java-forbindelse

  2. ProgrammingError:syntaksfejl ved eller nær ved udførelse af forespørgsel i python ved hjælp af psycopg2

  3. Simpel parametrering og trivielle planer — del 2

  4. Forbedre SQL INSERT-forespørgsel for at undgå sql-injektioner