Getting new IDs after insert

前端 未结 4 1796
我在风中等你
我在风中等你 2020-12-07 16:46

I\'m inserting a bunch of new rows into a table which is defined as follows:

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


        
相关标签:
4条回答
  • 2020-12-07 17:21

    create a table to set all the new IDs. then make a loop for all the insert. inside the loop make the insert you want with SCOPE_IDENTITY(). after the insert get the new ID and insert it into the new table you created for. in the end select * from [newTable].

    0 讨论(0)
  • 2020-12-07 17:24

    User this stored Procuedure

    this will be a dynamic primary key..

    
    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

    For More details visit following link http://jalpesh.blogspot.com/search?q=bulk+insert

    0 讨论(0)
  • 2020-12-07 17:25

    Use the OUTPUT functionality to grab all the INSERTED Id back into a table.

    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
    
    0 讨论(0)
  • 2020-12-07 17:30

    And if you want the "control" in ADO.Net and get the ids assigned to childs and getting the ids back so that you can update your model: http://daniel.wertheim.se/2010/10/24/c-batch-identity-inserts/

    0 讨论(0)
提交回复
热议问题