Search code examples
sql-server-2008auto-increment

SQL server insert multiple rows and incrementing a int column


I have some rows in a table and need to transfer them to another table. In the destination table i need also to add a field with an incremental value.

I'm doing the following, but i know that something in the insert is wrong, because the incremented value (intCodInterno) is always the same:

INSERT INTO Emp_VISOT.dbo.TBL_GCE_ARTIGOS
        ( strCodigo ,
          strDescricao ,
          intCodInterno ,
          intCodTaxaIvaCompra ,
          intCodTaxaIvaVenda ,
          strCodCategoria ,
          strAbrevMedStk ,
          strAbrevMedVnd ,
          strAbrevMedCmp ,
          bitAfectaIntrastat
        )(
        SELECT  A.Artigo ,
                a.Descricao ,
                IDENT_CURRENT('Emp_VISOT.dbo.TBL_GCE_ARTIGOS')+1,
                '3' ,
                '3' ,
                '1' ,
                'Un' ,
                'Un' ,
                'Un' ,
                '0'
        FROM PRIVESAM.DBO.Artigo A)

What do i need to change so the value is incremented correcty?

Thank you.

EDIT:

I made a small change in the query, and now it works. I just insert a SELECT in the IDENT_CURRENT inside brackets:

(SELECT IDENT_CURRENT('Emp_VISOT.dbo.TBL_GCE_ARTIGOS')+1)

I got all the rows that i need from the old table to the new with the incremented value.


Solution

  • the IDENT_CURRENT('Emp_VISOT.dbo.TBL_GCE_ARTIGOS')+1 evaluated once when you want to run the query and all the rows will get the same id.

    first solution is to iterate over the select result by a loop construct like cursor or whatsoever and insert the incremented index(you do that)

    second solution is to make that column in destination table identity