I am fairly new at writing procedures (beyond the basics)
I am trying to write a stored procedure that inserts into a table (dbo.billing_batch
) based on a select statement that loops through the list of results (@DealerID FROM dbo.vehicle_info
).
The SELECT DISTINCT...
statement on its own works perfectly and returns a list of 54 records.
The result of the SELECT
statement is dynamic and will change from week to week, so I cannot count on 54 records each time.
I am trying to use WHILE @DealerID IS NOT NULL
to loop through the INSERT
routine.
The loop is supposed to update dbo.billing_batch
, however it is inserting the same 1st record (BillingBatchRosterID, DealerID
) over and over and over to infinity.
I know I must be doing something wrong (I have never written a stored procedure that loops).
Any help would be greatly appreciated!
Here is the stored procedure code:
ALTER PROCEDURE [dbo].[sp_billing_batch_set]
@varBillingBatchRosterID int
AS
SET NOCOUNT ON;
BEGIN
DECLARE @DealerID int
SELECT DISTINCT @DealerID = vi.DealerID
FROM dbo.vehicle_info vi
LEFT JOIN dbo.dealer_info di ON di.DealerID = vi.DealerID
WHERE di.DealerActive = 1
AND (vi.ItemStatusID < 4 OR vi.ItemStatusID = 5 OR vi.ItemStatusID = 8)
END
WHILE @DealerID IS NOT NULL
BEGIN TRY
INSERT INTO dbo.billing_batch (BillingBatchRosterID, DealerID)
VALUES(@varBillingBatchRosterID, -- BillingBatchRosterID - int
@DealerID) -- DealerID - int
END TRY
BEGIN CATCH
SELECT ' There was an error: ' + error_message() AS ErrorDescription
END CATCH