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