I have to insert 7 rows into a table for each row found in a another table, I am currently doing this is my C# application, but it is dreadfully slow for a relatively small database.
I want to move this into one query, and the best method would be a foreach loop, SQL doesnt have this though so a WHILE loop will have to do.
However I cant even get to the insert part as I cannot loop through the rows, here is my SQL so far
DECLARE @cnt INT = 0;
SELECT ResNo FROM Res WHERE TSGrNo = 1;
print 'row cnt';
print @@RowCount; -- prints 0 even though 6 rows are returned
WHILE @cnt < @@Rowcount
BEGIN
print @cnt;
--In here I need to do this
-- INSERT INTO tbl (_,tbl.ResNo,_, _, _)
-- VALUES (_,Row.ResNo,_,_,_)
SET @cnt = @cnt + 1;
END
Does anyone know a better and working way to do this?
EDIT:
This is where I am at now
DECLARE @_R1 INT = 7, @_Date INT = 20150608
SELECT *
FROM Res r
WHERE NOT EXISTS
(
SELECT *
FROM Vis_ResR rr
WHERE rr.ResNo = r.ResNo
AND rr.Date = @_Date
)
AND r.TSGrNo = 1
AND r.R1 = @_R1
INSERT INTO Vis_ResR (R1, ResNo, Vis_ResR.Date, FrTm, ToTm)
VALUES (@_R1,r.ResNo,@_Date,0,0)
@_R1 and @_Date will be set before sending the query, I just don't understand how to make it INSERT using the r.ResNo values