Click here to Skip to main content
15,889,281 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
I have a table in production DB with ID int identity (1,1).
I am trying to add new data to it via SSIS but the table in STG has also the same int identity (1,1) which starts from 1 and I need to start from the max id from table in DB production.
Then i have a merge script that insert new data upon id
How should approach this?

What I have tried:

I have tried to change the store procedure:
CREATE PROCEDURE spmaxid
as 
BEGIN 
	SELECT  max([ID])
FROM [Production].[dbo].[UNITS] 
END


then this:
UPDATE [dbo].[STG UNITS] SET id = NULL
GO 

DECLARE @id INT 
SET @id =  Spmaxid
UPDATE [STG].[dbo].[STG UNITS] 
SET @id = id = @id + 1
GO 

SELECT * FROM [STG UNITS] 
GO
Posted
Updated 13-Dec-20 21:38pm

The simple solution would be:
SQL
DECLARE @MaxId int;
SELECT @MaxId = MAX(ID) FROM Production.dbo.UNITS;

UPDATE
    STG.dbo.[STG UNITS]
SET
    id = IsNull(@MaxId, 0) + id
;

If your staging table has gaps in the IDs, and you want to get rid of the gaps:
SQL
DECLARE @MaxId int;
SELECT @MaxId = MAX(ID) FROM Production.dbo.UNITS;

WITH cte As
(
    SELECT
        id,
        ROW_NUMBER() OVER (ORDER BY id) As RN
    FROM
       STG.dbo.[STG UNITS] 
)
UPDATE 
    S
SET 
    id = IsNull(@MaxId, 0) + R.RN
FROM
    STG.dbo.[STG UNITS] As S
    INNER JOIN cte As R ON R.id = S.id
;
 
Share this answer
 
In addition to Solution 1 and in response the OP comment in a solution
You cannot update identity columns without a little bit of extra work

e.g.
SQL
SET IDENTITY INSERT STG.dbo.[STG UNITS] ON
see SET IDENTITY_INSERT (Transact-SQL) - SQL Server | Microsoft Docs[^]. Do what you need to do in terms of inserting the new records, and then remember to
SQL
SET IDENTITY INSERT STG.dbo.[STG UNITS] OFF
OR
You can use DBCC CHECKIDENT (Transact-SQL) - SQL Server | Microsoft Docs[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900