2012-09-13 11 views
7
DECLARE @t2 AS TABLE(id INT) 

INSERT INTO dbo.EntityMaster 
     (EntityType) 
OUTPUT INSERTED.EntityId INTO @t2 
SELECT 'G' FROM #tmp 

#tmp è una tabella temporanea che contiene dati caricati da un xml. Devo generare EntityId per ogni record contenuto in #tmp. Esso può essere fatto inserendo primo record nella tabella EntityMaster quindi inserire questo EntityID resta in #tmp per ogni record.Come utilizzare la clausola OUTPUT di SQL Server per l'aggiornamento

Invece di inserire record in @t2, è necessario aggiornare #tmp per ogni record.

Qualsiasi possibilità?

+0

Come identificheresti quale record in #tmp va con quale entityid? – HLGEM

+0

@HLGEM: Stavo pensando la stessa cosa, ma ho avuto l'idea di prendere campo GUID nella colonna EntityMaster che verrà generato da frontend e sarà sempre unico. Usando questo, posso associare ogni record di EntityMaster –

risposta

1

provare qualcosa di simile, è ancora necessario utilizzare la tabella temporanea, ma non è troppo male per leggere e si ottiene il lavoro fatto.

 
CREATE TABLE #tmp 
(
    tmpID INT IDENTITY(1,1) PRIMARY KEY CLUSTERED, 
    xmlData VARCHAR(255), 
    EntityId INT 
) 
DECLARE @t2 TABLE 
(
    tmpID INT, 
    EntityId INT 
) 

MERGE dbo.EntityMaster AS EM 
USING 
(
    SELECT tmpID, 
     xmlData, 
     EntityId 
    FROM #tmp 
) AS X 
    ON EM.EntityId = X.EntityId 
WHEN NOT MATCHED THEN 
    INSERT (EntityType) 
    VALUES (X.xmlData) 
OUTPUT X.tmpID, INSERTED.EntityId 
INTO @t2 (tmpID, EntityId); 

UPDATE T 
SET EntityId = T2.EntityId 
FROM @t2 T2 
INNER JOIN #tmp T 
    ON T2.tmpID = T.tmpID 

+0

bello! Mi piace la tua risposta;) –

0

Questo sarebbe più facile da realizzare in SQL che inserisce i record XML nella tabella #tmp.

consideri il @recs tabella seguente, che potrebbe essere pensato come un insieme di record generato da XML:

declare @recs table (val varchar(255)) 
insert into @recs values ('this'), ('is'), ('a'), ('test') 

è possibile aggiungere facilmente un intero incremento per ciascun record in questo modo:

select row_number() over (order by (select 1)) as id, val from @recs 

Il risultato è il seguente:

id val 
1 this 
2 is 
3 a 
4 test 

Potrebbe utilizzare row_number() over (order by (select1)) per generare gli ID necessari allo stesso tempo i record vengono inseriti in #tmp?

Problemi correlati