Ottenere nuovi ID dopo l'inserimento
-
03-07-2019 - |
Domanda
Sto inserendo un mucchio di nuove righe in una tabella che è definita come segue:
CREATE TABLE [sometable](
[id] [int] IDENTITY(1,1) NOT NULL,
[someval] sometype NOT NULL
)
utilizzando il seguente inserto:
insert into sometable select somefield as someval from othertable
quando avrò finito, vorrei conoscere gli ID di tutte le righe appena inserite. SCOPE_IDENTITY () restituisce solo l'ID ultima riga inserita.
Come posso ottenere tutti i nuovi ID?
Un metodo che mi viene in mente sarebbe quello di catturare l'attuale più grande identità da qualcosa e il scope_identity () post-inserimento, e usare questi due valori per selezionare da qualcosa. Ad esempio:
declare @currentMaxId int;
select @currentMaxId=MAX(id) from sometable
insert into sometable select somefield as someval from othertable
select * from sometable where id>@currentMaxId and id<=SCOPE_IDENTITY()
Esiste un modello migliore?
Soluzione
Utilizzare la funzionalità OUTPUT per recuperare tutti gli ID INSERTED in una tabella.
CREATE TABLE MyTable
(
MyPK INT IDENTITY(1,1) NOT NULL,
MyColumn NVARCHAR(1000)
)
DECLARE @myNewPKTable TABLE (myNewPK INT)
INSERT INTO
MyTable
(
MyColumn
)
OUTPUT INSERTED.MyPK INTO @myNewPKTable
SELECT
sysobjects.name
FROM
sysobjects
SELECT * FROM @myNewPKTable
Altri suggerimenti
E se vuoi il "controllo" " in ADO.Net e ottenere gli ID assegnati ai figli e recuperarli in modo da poter aggiornare il modello: http://daniel.wertheim.se/2010/10/ 24 / C-batch identità-inserti /
Utente questa procedura memorizzata
questa sarà una chiave primaria dinamica ..
SET QUOTED_IDENTIFIER ON
GO
SET ANSI_NULLS ON
GO
CREATE PROCEDURE sp_BulkInsertCountry
(
@FilePath varchar(1000)
)
AS
BEGIN--PROCEDURE
--variable declaration
declare @SQL varchar(500)
declare @id int
declare @CountryName varchar(30)
--Create temporary table for Country
CREATE TABLE #tmpCountry
(
CountryName varchar(30),
)
---executing bulk insert on temporary table
SET @SQL='BULK INSERT #tmpCountry from ''' + @FilePath + ''' WITH (FIELDTERMINATOR ='','',ROWTERMINATOR=''\n'')'
EXEC(@sql)
DECLARE cursor_Country CURSOR READ_ONLY FOR
select [CountryName] from #tmpCountry
OPEN cursor_Country
FETCH NEXT FROM cursor_Country INTO @CountryName
WHILE @@FETCH_STATUS=0
BEGIN
SELECT @id=isnull(max(Countryid),0) from tblCountryMaster
SET @id=@id+1
INSERT INTO tblCountryMaster values(@Id,@CountryName)
FETCH NEXT FROM cursor_Country INTO @CountryName
END
CLOSE cursor_Country
DEALLOCATE cursor_Country
END--PROCEDURE
GO
SET QUOTED_IDENTIFIER OFF
GO
SET ANSI_NULLS ON
GO
Per maggiori dettagli visita il seguente link http://jalpesh.blogspot.com/search?q=bulk+insert
crea una tabella per impostare tutti i nuovi ID. quindi crea un ciclo per tutto l'inserto. all'interno del ciclo crea l'inserto desiderato con SCOPE_IDENTITY (). dopo l'inserimento ottieni il nuovo ID e inseriscilo nella nuova tabella per cui hai creato. alla fine seleziona * da [newTable].