Obter novos IDs após inserção
-
03-07-2019 - |
Pergunta
Eu estou inserindo um monte de novas linhas em uma tabela que é definida da seguinte forma:
CREATE TABLE [sometable](
[id] [int] IDENTITY(1,1) NOT NULL,
[someval] sometype NOT NULL
)
usando o seguinte inserção:
insert into sometable select somefield as someval from othertable
quando eu terminar, eu gostaria de saber os IDs de todas as linhas recém-inseridas. SCOPE_IDENTITY () retorna apenas o ID última linha inserida.
Como posso obter todas as novas IDs?
Um método que vem à mente seria para pegar o maior identidade atual da sometable eo SCOPE_IDENTITY () pós-inserção, e usar esses dois valores para selecionar sometable. Por exemplo:
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()
Existe um padrão melhor?
Solução
Use a funcionalidade de saída para pegar toda a volta INSERTED Id em uma tabela.
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
Outras dicas
E se você quiser o "controle" no ADO.Net e obter os IDs atribuídos a criança e obter os ids para trás para que você pode atualizar o seu modelo: http://daniel.wertheim.se/2010/10/ 24 / c-lote-identidade-inserções /
Usuário esta armazenado Procuedure
este será uma chave primária dinâmico ..
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 mais detalhes visite o seguinte link de http://jalpesh.blogspot.com/search?q=bulk+insert
criar uma tabela para definir todas as novas identificações. em seguida, fazer um laço para toda a inserção. dentro do loop fazer a inserção quiser com SCOPE_IDENTITY (). após a inserção de obter o novo ID e inseri-lo para a nova tabela que você criou para. no final SELECT * FROM [newtable].