martes, 8 de abril de 2014

Extract postal code 4 and 5 numeric values from the last part address in SQL

EXEC EXTRACT_CP 'PROL LUIS PONCE PRIN NO 12345   LA MORENA 17237 COYOACAN'
EXEC EXTRACT_CP 'PROL LUIS PONCE PRIN NO 1234   RINCONADA 7237 COYOACAN'
GO

ALTER PROCEDURE EXTRACT_CP

@str VARCHAR(MAX)
AS
BEGIN

DECLARE @tmp VARCHAR(MAX)

SELECT @tmp = @str

SELECT @tmp = 

REVERSE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(REPLACE(
@tmp,'9','@'),'8','@'),'7','@'),'6','@'),'5','@'),'4','@'),'3','@'),'2','@'),'1','@'),'0','@'))

DECLARE @pos INT

IF (CHARINDEX('@@@@@', @tmp) = 0)

BEGIN
SELECT @pos = CHARINDEX('@@@@', @tmp)
SELECT @tmp = '0'
SELECT @tmp = @tmp + REVERSE(SUBSTRING(REVERSE(@str), @pos, 4))
END
ELSE
BEGIN
SELECT @pos = CHARINDEX('@@@@@', @tmp)
SELECT @tmp = REVERSE(SUBSTRING(REVERSE(@str), @pos, 5))
END

SELECT @tmp


END

GO