基于父ID,将子表中的所有行复制到具有新Id的子表中

时间:2013-10-08 05:53:45

标签: .net sql database sql-server-2008 tsql

我有一个父表,用于存储Employee的数据及其子表的工资,存储有关特定员工薪水的所有数据在EmployeeId的基础上我希望获得所有工资行并将其再次插入工资表使用不同的Id我无法使Id自动增加。我需要使用存储过程执行此操作。

先谢谢。

我正在使用Sqlserver 2008。

Employee Table
Id Name      Country 
1. Employee1 Pakistan
2. Employee2 India

Salary Table
Id EmployeeId Month Salary
1. 1          Jan   20000
2. 1          feb   25000
3. 1          Mar   30000

现在我有了员工ID 1,我希望从工资表中获取所有行,然后将它们再次插入到带有新ID的同一工资表中。

4 个答案:

答案 0 :(得分:2)

嗯,据我所知,你应该可以做到

DECLARE @NewID INT = 2

INSERT INTO Salary (EmployeeId,Month,Salary)
SELECT @NewID, Month, Salary
FROM Salary
WHERE EmployeeId = 1

SQL Fiddle DEMO

答案 1 :(得分:0)

是你想要的东西

DECLARE @NewID INT 

set @NewID=(select top 1 id from Employee e left join salary s on e.id=s.EmployeeId where s.id is null)
INSERT INTO Salary (EmployeeId,Month,Salary)
SELECT @NewID, Month, Salary
FROM Salary
WHERE EmployeeId = 1

答案 2 :(得分:0)

CREATE PROC INSERTDETAILS1 (@EmpID int)
AS
BEGIN
DECLARE @Sal NUMERIC(18,2)

DECLARE Sal_Cursor CURSOR -- Declare cursor

LOCAL SCROLL STATIC

FOR

Select Salary FROM EmpSal where EmpID=@EmpID

OPEN Sal_Cursor -- open the cursor

FETCH NEXT FROM Sal_Cursor

   INTO @Sal

   INSERT INTO EmpSal VALUES ((SELECT TOP(1) EmpID FROM EmpSal ORDER BY EmpID DESC)+1,@Sal)


WHILE @@FETCH_STATUS = 0

BEGIN

   FETCH NEXT FROM Sal_Cursor

   INTO @Sal

   INSERT INTO EmpSal VALUES ((SELECT TOP(1) EmpID FROM EmpSal ORDER BY EmpID DESC)+1,@Sal)

END


CLOSE Sal_Cursor -- close the cursor

DEALLOCATE Sal_Cursor -- Deallocate the cursor

END

答案 3 :(得分:0)

如果Salary.Id不是,而不是IDENTITY列,您可以使用ROW_NUMBER函数将行号分配给您正在复制的子集,并将其添加到最后一个表中的Id值用于获取新的Id s:

INSERT INTO Salary (Id, EmployeeId, Month, Salary)
SELECT
  Id         = (SELECT MAX(Id) FROM Salary) + ROW_NUMBER() OVER (ORDER BY Id),
  EmployeeId = @NewEmpId,
  Month,
  Salary
FROM Salary
WHERE EmployeeId = @SrcEmpId
;