将记录插入表中,根据刚刚插入的记录更新下一个序列号,然后插入下一条记录

时间:2014-09-17 22:44:34

标签: sql sql-server

我将依赖信息(儿童,兄弟姐妹等)插入员工福利表。对于添加的每个新依赖项,有一个序列号字段增加16,384。正在插入的数据是从另一个表中选择的,并且每个员工的变量行数基于受抚养人数。

问题是,在插入每条记录之后,我需要根据我刚插入的每位员工现有表格中已有的最大序列号,将下一个序列号增加16,384。

我试图研究和测试“Cursor”和“While”循环但没有成功......此外,似乎社区通常建议远离这两种方式。

这是当前代码,它返回错误,我正在复制序列号。

--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

在尝试使用wewesthemenace建议的代码但将* 16384更改为+ 16384之后,以下是来自源,目标和结果的示例数据的屏幕截图: enter image description here

1 个答案:

答案 0 :(得分:0)

这使用row_number()来确定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