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:
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
- In the DataFlow Task Add a Script Component
- Add an Output Column of type
DT_I4
(ex: NewID
)
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
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:
- Create a staging table with an identity column
- Each time Truncate the Table (this will restart identity), and Insert data into staging table
- Insert data from Staging table using a
DataFlow Task
or an Execute SQL Task
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
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