I am trying to Parse Address information passed in as a comma separated string. I have gotten as far as parsing down the information as I need using this pseudo sample
CREATE TRIGGER aftInsParseAddress
AFTER INSERT
AS
DECLARE @address VARCHAR(100),
@city VARCHAR(100),
@stateZip VARCHAR(100),
@source varchar(100),
@state varchar(2) ,
@zip varchar(5),
@country1 varchar(10) ,
@country varchar(3)
SET @source = (SELECT AddressSourceA
FROM table
WHERE ID = 'GUID-GUID-GUID-GUID-GUID' AND Exported = 0)
SELECT
@address = LEFT(@source, CHARINDEX(',', @source) - 1),
@city = (SUBSTRING (@source, CHARINDEX(',', @source) + 2 ,
CHARINDEX(',', @source, CHARINDEX(',', @source) + 1) - LEN(LEFT(@source, CHARINDEX(',', @source) )) -2)),
@stateZip = SUBSTRING(@source, CHARINDEX(',', @source, LEN(@city) + LEN(@address)), 10),
@state = (SUBSTRING(@stateZip, 3 ,4)),
@zip = (SUBSTRING(@stateZip, 6, 9)),
@country1 = (SUBSTRING(@source, (CHARINDEX(',', @source, LEN(@address) + LEN(@statezip) + LEN(@city) )), 5)),
@country = (SUBSTRING(@country1, 3, 7))
UPDATE SameTableInsertedInto
SET Address = @address, City = @city,
State = @state, Zip = @zip,
Country = @country
WHERE id IN (SELECT ID FROM inserted);
I would start with a string as my @source = '1600 Pennsylvania Ave NW, Washington, DC 20500, USA'
Ending up with the values parsed out how I need them i.e.
1600 Pennsylvania Ave NW
Washington
DC
20500
USA
I'm importing this data from a web form that the creator isn't capable of parsing the address on their end. As a result I need each address field split up in its own variable. I have built a sample that does this and tried to implement this in a trigger on after insert then update the same fields in the destination table.
I am able to build a working sample of successfully triggering 1 record but in more often I would be importing multiple records. I'm not sure where to head next with this to fix my dilemma. Should I be parsing the data within a stored procedure or function ?
Also important to note. I am attempting to run this trigger after I insert records into my table, and update values within the same table the the new values are going into.
Thanks in advance for any help !