简体   繁体   中英

Insert record to a table, update next sequence number based on record just inserted, then insert next record

I'm inserting dependent information (children, siblings, etc) to an employee benefits table. There is a sequence number field that increments by 16,384 for each new dependent added. The data being inserted is selected from another table and has variable rows per employee based on number of dependents.

The issue is that after each record is inserted, I need the next sequence number to be incremented by 16,384 based on the maximum sequence number already in the existing table per employee that I just inserted to.

I've attempted to research and test "Cursor" and "While" looping without success...also, it seems the community typically suggests staying away from both of these anyway.

Here is current code which is returning errors that I'm duplicating the sequence number.

--Create Temp Table to hold next Sequence Number Per employee
select EMPLOYID,MAX(seqnumbr)+16384 as NextNum 
into #NextSeqNum from EmployeeDependentTable 
     group by EMPLOYID

--Set up Counter of times to loop
DECLARE @counter INT;
SET @counter=1;
WHILE @counter < 100

--Start Loop
BEGIN 
   INSERT INTO EmployeeDependentTable
           ([EMPLOYID]
           ,[SEQNUMBR]
           ,[RELATIONSHIP]
           ,[FRSTNAME]
           ,[LASTNAME])
  SELECT 
     d.employid,
     s.NextNum, 
     relationship,
     firstname,
     lastname
  FROM DependentDataTable d
     left outer join
     #NextSeqNum s
     on s.EMPLOYID=d.employid

--Drop and recreate Next Sequence Number to be ready for next loop
drop table #NextSeqNum
select EMPLOYID,MAX(seqnumbr)+16384 as NextNum 
into #NextSeqNum from UPR00111 
     group by EMPLOYID

--Increase Loop Counter by 1
set @counter=@counter+1

END

After attempting to use code suggested by wewesthemenace but altering the * 16384 to be + 16384, here is screenshot of sample data from source, destination, and results: 在此处输入图片说明

This uses row_number() to determine the SEQNUMBER .

DECLARE @maxSeqNum INT
SELECT TOP 1 @maxSeqNum = MAX(SEQNUMBER) FROM EmployeeDependentTable GROUP BY EMPLOYID ORDER BY MAX(SEQNUMBER) DESC

;WITH cte AS(
    SELECT
        *,
        (row_number() OVER(ORDER BY EMPLOYID) + @maxSeqNum)  * 16384 AS rn
    from DependentDataTable
)
INSERT INTO EmployeeDependentTable(
    [EMPLOYID],
    [SEQNUMBR],
    [RELATIONSHIP],
    [FRSTNAME],
    [LASTNAME]
)
SELECT
    employId,
    rn,
    relationship,
    firstname,
    lastname
FROM cte

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM