for each in MS SQL SERVER? for each in MS SQL SERVER? sql-server sql-server

for each in MS SQL SERVER?


If you really require a loop, you can use a cursor. They are horribly inefficient, so you should avoid unless you absolutely require it:

DECLARE c CURSOR READ_ONLY FAST_FORWARD FOR    SELECT EmployeeID    FROM EmployeesDECLARE @id Int-- Open the cursorOPEN cFETCH NEXT FROM c INTO @idWHILE (@@FETCH_STATUS = 0)BEGIN    INSERT INTO EmployeePayroll    SELECT 0, @id, 0, 0, 0    -- do other stuff    FETCH NEXT FROM c INTO @idEND-- Close and deallocate the cursorCLOSE cDEALLOCATE c


Use the following statement:

INSERT INTO EmployeePayrollSELECT  0,EmployeeID ,0,0,0FROM  Employees

You can check for the existance of the record before inserting it by appending:

WHERE  ID NOT IN  (     SELECT       EmployeeID     FROM       EmployeePayroll  )


This is the one way to achieve your requirement using While loop & Temp table variable,

The sample query is given below,

--: Get the Employees table data & insert this to temp table variableDeclare @TempEmpTbl Table (RowId int identity, EmployeeID int, EmployeeName nvarchar(100), EmployeeStatus int, BasicSalary int);Insert into @TempEmpTbl Select * from Employees;--: temp variablesDeclare @TempEmpCount Int = (Select Count(RowId) From @TempEmpTbl);Declare @MinCount Int = 1;Declare @GetEmpId int;--: while loop for EmployeePayroll tbl insertion based on Employees dataWhile(@TempEmpCount >= @MinCount)Begin    Set @GetEmpId = (Select EmployeeID From @TempEmpTbl Where RowId = @MinCount);       Insert into EmployeePayroll values (0, @GetEmpId,0 ,0 ,0)    Set @MinCount = @MinCount + 1;End

Note : Suppose the employee record is already there, we can able to update EmployeePayroll records from within this while loop.