07-31-2023, 03:12 AM
I came up with a very effective and (I think) readable way to do this.
1. Create a temp table and put the records you want to iterate in there
2. Use `WHILE @@ROWCOUNT <> 0` to do the iterating
3. To get one row at a time do, `SELECT TOP 1 <fieldnames>`
b. save the unique ID for that row in a variable
4. Do stuff, then delete the row from the temp table based on the ID saved at step 3b.
Here's the code. Sorry, its using my variable names instead of the ones in the question.
DECLARE @tempPFRunStops TABLE (
ProformaRunStopsID int,
ProformaRunMasterID int,
CompanyLocationID int,
StopSequence int
);
INSERT @tempPFRunStops (ProformaRunStopsID, ProformaRunMasterID, CompanyLocationID, StopSequence)
SELECT
ProformaRunStopsID,
ProformaRunMasterID,
CompanyLocationID,
StopSequence
FROM ProformaRunStops
WHERE ProformaRunMasterID IN (
SELECT ProformaRunMasterID
FROM ProformaRunMaster
WHERE ProformaId = 15 )
-- SELECT * FROM @tempPFRunStops
WHILE @@ROWCOUNT <> 0 -- << I dont know how this works
BEGIN
SELECT TOP 1 * FROM @tempPFRunStops
-- I could have put the unique ID into a variable here
SELECT 'Ha' -- Do Stuff
DELETE @tempPFRunStops
WHERE ProformaRunStopsID = (SELECT TOP 1 ProformaRunStopsID FROM @tempPFRunStops)
END
1. Create a temp table and put the records you want to iterate in there
2. Use `WHILE @@ROWCOUNT <> 0` to do the iterating
3. To get one row at a time do, `SELECT TOP 1 <fieldnames>`
b. save the unique ID for that row in a variable
4. Do stuff, then delete the row from the temp table based on the ID saved at step 3b.
Here's the code. Sorry, its using my variable names instead of the ones in the question.
DECLARE @tempPFRunStops TABLE (
ProformaRunStopsID int,
ProformaRunMasterID int,
CompanyLocationID int,
StopSequence int
);
INSERT @tempPFRunStops (ProformaRunStopsID, ProformaRunMasterID, CompanyLocationID, StopSequence)
SELECT
ProformaRunStopsID,
ProformaRunMasterID,
CompanyLocationID,
StopSequence
FROM ProformaRunStops
WHERE ProformaRunMasterID IN (
SELECT ProformaRunMasterID
FROM ProformaRunMaster
WHERE ProformaId = 15 )
-- SELECT * FROM @tempPFRunStops
WHILE @@ROWCOUNT <> 0 -- << I dont know how this works
BEGIN
SELECT TOP 1 * FROM @tempPFRunStops
-- I could have put the unique ID into a variable here
SELECT 'Ha' -- Do Stuff
DELETE @tempPFRunStops
WHERE ProformaRunStopsID = (SELECT TOP 1 ProformaRunStopsID FROM @tempPFRunStops)
END