0

I want to insert into table B for a range of employees from table A where the select statement for the insert is from table B. To restate that; I have created all the records I need in table B for one employee (employeeid = 1). Now I want to insert into table B similar records for a range of employees in table A.

so far I have

insert TABLEB as B
(EMPLOYEEID, COLUMN1, COLUMN2, COLUMN3)
     SELECT A.EMPLOYEEID, B.COLUMN1, B.COLUMN2, B.COLUMN3 
     FROM TABLEB 
     WHERE EMPLOYEEID = 1

now I want that to insert for each row in Table A that meets a selecion criteria

the above works for one employee. How do I make it iterate for a range of employees from table A. note that the EMPLOYEEID I want to insert for each row in table B will be the ID from the employee in table A.

Thanks,

Veera
  • 3,412
  • 2
  • 14
  • 27
davidb
  • 21
  • 1

3 Answers3

0

Try the below query:

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
J0e3gan
  • 8,740
  • 10
  • 53
  • 80
Imtiaz Ali
  • 13
  • 1
  • 6
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)
vinayak
  • 67
  • 3
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

Note: The loop idea was copied from What are the most common SQL anti-patterns? and modified (because I think there was a typo in the answer).

Community
  • 1
  • 1
davidb
  • 21
  • 1