0

我有一个父表,它存储 Employee 的数据,它的子表 Salary 存储有关特定员工薪水的所有数据基于 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

4 回答 4

2

好吧,据我了解,您应该可以做到

DECLARE @NewID INT = 2

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

SQL 小提琴演示

于 2013-10-08T06:08:48.207 回答
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
于 2013-10-08T06:38:13.747 回答
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
;
于 2013-10-09T18:25:28.927 回答
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
于 2013-10-08T06:57:50.613 回答