插入到表A中,从表A中选择B,其中条件来自B,对于满足B中条件的每个记录

时间:2014-11-17 07:06:54

标签: sql sql-server

我想在table B中为来自table A select insert table B语句table B的{​​{1}}一系列员工插入insert。 重申一下;我在into table B为一个员工(employeeid = 1)创建了我需要的所有记录。现在,我希望在table A中为一系列员工提供insert TABLEB as B (EMPLOYEEID, COLUMN1, COLUMN2, COLUMN3) SELECT A.EMPLOYEEID, B.COLUMN1, B.COLUMN2, B.COLUMN3 FROM TABLEB WHERE EMPLOYEEID = 1 Table A个类似记录。

到目前为止我已经

table A

现在我希望为符合选择标准的table B中的每一行插入

以上为一名员工工作。如何使table A.的一系列员工进行迭代。 请注意,我要为{{1}}中的每一行插入的EMPLOYEEID将是{{1}}

中员工的ID

谢谢,

3 个答案:

答案 0 :(得分:0)

尝试以下查询:

insert TABLEB as B (EMPLOYEEID, COLUMN1, COLUMN2, COLUMN3) 
SELECT A.EMPLOYEEID, A.COLUMN1, A.COLUMN2, A.COLUMN3 
FROM TABLEA 
WHERE A.EMPLOYEEID between 1 and 13

答案 1 :(得分:0)

INSERT INTO TABLEB (EMPLOYEEID, COLUMN1, COLUMN2, COLUMN3)
SELECT B.EMPLOYEEID, A.COLUMN1, A.COLUMN2, A.COLUMN3 
FROM TABLEB As B
JOIN TABLEA AS A ON(A.EMPLOYEEID=B.EMPLOYEEID)

答案 2 :(得分:0)

declare @loopVar int
Set @loopVar = (select min(employeeid) from mast.employee as e 
                where e.JobTitle = 'Night Cook')

while @loopVar is not null

begin

insert mast.PayProfile
(EmployeeID, PayitemCode, PayItem, EarningId, AllowanceId, 
 Quantity, Rate, Amount, BaseRate, ApplySalarySacrifice)
(select @loopvar, PayitemCode, PayItem, EarningId, AllowanceId, 
 Quantity, Rate, Amount, BaseRate, ApplySalarySacrifice 
 from mast.payprofile as pp
 join mast.Employee as e on e.EmployeeId = pp.EmployeeId 
 where pp.EmployeeId = 224 
 and (earningid is not null or allowanceid is not null))

Set @loopVar = (select min(employeeid) from mast.Employee 
                where EmployeeId>@loopVar and JobTitle='Night Cook' 
                and IsTerminated = 0)
end

注意:循环创意是从What are the most common SQL anti-patterns?复制并修改的(因为我认为答案中存在拼写错误)。