Add incremental number while inserting records using SSIS

为君一笑 提交于 2019-11-30 09:48:36

问题


I have a SSIS package in which, two records are coming. I need to insert the records in the table with an extra column (let's say Sequence). If there are two records, Sequence column should have the value 1(for the first record) and 2(for the second record). Again, next time, I'm getting three records, then again sequence starts from 1,2 and 3.

Is there anyway to do this without using script or stored procedure?

Screenshot:


回答1:


There are 2 methods to achieve this:

(1) why not using a script component?

I think that using script component is more efficient and more controlled, you can write your own logic

  1. In the DataFlow Task Add a Script Component
  2. Add an Output Column of type DT_I4 (ex: NewID)
  3. In the Script Editor use the following Code (i used Visual Basic language)

    Imports System  
    Imports System.Data  
    Imports System.Math  
    Imports Microsoft.SqlServer.Dts.Pipeline.Wrapper  
    Imports Microsoft.SqlServer.Dts.Runtime.Wrapper  
    
    <Microsoft.SqlServer.Dts.Pipeline.SSISScriptComponentEntryPointAttribute> _  
    <CLSCompliant(False)> _  
    Public Class ScriptMain  
        Inherits UserComponent 
    
        Private CurrentID as Integer  = 0
    
    
        Public Overrides Sub Input0_ProcessInputRow(ByVal Row As Input0Buffer)  
    
            CurrentID += 1
    
            Row.NewID = CurrentID
    
    
        End Sub 
    
    End Class
    
  4. In the OLEDB Destination,Map the NewID column to the destination identity column

(2) Using Staging Table

As similar to what i mentioned in this answer:

  1. Create a staging table with an identity column
  2. Each time Truncate the Table (this will restart identity), and Insert data into staging table
  3. Insert data from Staging table using a DataFlow Task or an Execute SQL Task



回答2:


You can use a staging table with an IDENTITY(1,1) column, each time you execute the package you have to TRUNCATE the table to reset IDENTITY. So each time it will start from 1

Or you can write your own logic using a Script Component




回答3:


You can achieve this in the Database itself without the need of adding a Logic in the SSIS package. Just add a Column to your Destination table with IDENTITY and it will be automatically incremented. There is No Need to add Some Additional Logic in SSIS

You Can Add the IDENTITY Column (If you don't have one already on the Table) by Just altering your Table

ALTER TABLE YourTable
ADD SeqNo INT IDENTITY(1,1)

IDENTITY(1,1) Mens the Value of SeqNo for the First Record will be 1 and then it will be Incremented by 1 for each record inserted



来源:https://stackoverflow.com/questions/48378058/add-incremental-number-while-inserting-records-using-ssis

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!