Pregunta

Estoy insertando un montón de nuevas filas en una tabla que se define de la siguiente manera:

CREATE TABLE [sometable](
    [id] [int] IDENTITY(1,1) NOT NULL,
    [someval] sometype NOT NULL
)

utilizando el siguiente inserto:

insert into sometable select somefield as someval from othertable

cuando haya terminado, me gustaría saber los ID de todas las filas recién insertadas. SCOPE_IDENTITY () solo devuelve la última fila de ID insertada.

¿Cómo puedo obtener todos los nuevos ID?

Un método que viene a la mente sería agarrar la identidad más grande actual de sometable y scope_identity () post-insert, y usar estos dos valores para seleccionar de sometable. Por ejemplo:

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()

¿Hay un patrón mejor?

¿Fue útil?

Solución

Use la funcionalidad de SALIDA para agarrar todo el ID INSERTADO de nuevo en una tabla.

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

Otros consejos

Y si quieres el " control " en ADO.Net y obtenga los identificadores asignados a los niños y recupérelos para que pueda actualizar su modelo: http://daniel.wertheim.se/2010/10/ 24 / c-batch-identity-inserts /

Usuario este Procuedure almacenado

esta será una clave principal dinámica ..


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

Para más detalles visite el siguiente enlace http://jalpesh.blogspot.com/search?q=bulk+insert

crea una tabla para establecer todos los nuevos ID. luego hacer un bucle para todo el inserto. dentro del bucle haga la inserción que desee con SCOPE_IDENTITY (). después de la inserción, obtenga el nuevo ID e insértelo en la nueva tabla que creó. al final, seleccione * de [tabla nueva].

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top