I have a list of about 55k Accounts that I am cleaning up. 95% of them are from US/Canada which is what I'm most concerned with. I am going through record by record and will perform various checks and fill in or correct City, State, Zip, Country. I have a table with every City, State, and Zip for US and Canada that I check against. For this part, maybe 20% will be processed after grabbing the info.
I am doing a kind of proof of concept right now, and it's taking forever. I just hit the 1hr mark with 24,500 (Less than 7 records/sec) . I didn't expect this to take so long. Next will be running a similar process on the Contacts, and there are over 400k contacts. I'm afraid how long that will take!!
Is there a better way to do this to decrease the time taken?
Here is the code right now:
-- MS SQL Server 15.0.2070.41
ALTER PROCEDURE [dbo].[SetLocationInfo]
AS
BEGIN
DECLARE
@maxRecords int = 0,
@cnt int = 1,
@city varchar(255),
@state varchar(255),
@zip varchar(255),
@country varchar(255)
SELECT TOP(1) @maxRecords = id2 FROM Account ORDER BY Id2 DESC
-- BEGIN LOOP
WHILE @cnt <= @maxRecords
BEGIN
-- Resets Variables
SET @city = NULL
SET @state = NULL
SET @zip = NULL
SET @country = NULL
-- Pulls BILLING Address Info from Record
SELECT
@city = [BillingCity],
@state = [BillingState],
@zip = [BillingPostalCode],
@country = [BillingCountry]
FROM [Account] WHERE Id2 = @cnt
-- Searches for and Sets BILLING Country
IF (@country IS NULL) OR ((@country != 'United States') AND (@country != 'Canada'))
BEGIN
SELECT TOP(1) @country = Country FROM [CityStateInfo]
WHERE
(City = @city AND State_abbr = @state) OR
(City = @city AND Zip = LEFT(@zip,5)) OR
(Zip = LEFT(@zip,5))
IF @country IS NOT NULL
UPDATE Account SET [BillingCountry] = @country WHERE Id2 = @cnt
END
-- Resets Variables
SET @city = NULL
SET @state = NULL
SET @zip = NULL
SET @country = NULL
-- Pulls SHIPPING Address Info from Record
SELECT
@city = [ShippingCity],
@state = [ShippingState],
@zip = [ShippingPostalCode],
@country = [ShippingCountry]
FROM [Account] WHERE Id2 = @cnt
-- Searches for and Sets SHIPPING Country
IF (@country IS NULL) OR ((@country != 'United States') AND (@country != 'Canada'))
BEGIN
SELECT TOP(1) @country = Country FROM [CityStateInfo]
WHERE
(City = @city AND State_abbr = @state) OR
(City = @city AND Zip = LEFT(@zip,5)) OR
(Zip = LEFT(@zip,5))
IF @country IS NOT NULL
BEGIN
PRINT CAST(@cnt AS varchar(10)) + ': ' + @country
UPDATE Account SET [ShippingCountry] = @country WHERE Id2 = @cnt
END
END
-- Increments Counter
SET @cnt = @cnt + 1
END
-- END LOOP
END