I am creating a function in which I will check if a endereço_A
contains parts in a endereço_B
, exemplifying:
address_A
AVENIDA JOÃO E MARIA
B_address
RUA JOÃO
The result should return JOÃO
, which is the substring that both addresses have in common.
CREATE FUNCTION dbo.splitSearchAddress ( @addressSearch VARCHAR(MAX), @addressIn VARCHAR(MAX) )
RETURNS
@returnList TABLE ([Name] [nvarchar] (500))
AS
BEGIN
DECLARE @name NVARCHAR(255)
DECLARE @pos INT
DECLARE @separator CHAR(1)
SET @separator = ' '
WHILE CHARINDEX(@separator, @addressSearch) > 0
BEGIN
SELECT @pos = CHARINDEX(@separator, @addressSearch)
SELECT @name = SUBSTRING(@addressSearch, 1, @pos-1)
IF CHARINDEX(@name, @addressIn) > 0
BEGIN
INSERT INTO @returnList
SELECT @name
END
SELECT @addressSearch = SUBSTRING(@addressSearch, @pos+1, LEN(@addressSearch)-@pos)
END
INSERT INTO @returnList
SELECT ISNULL(@addressSearch, 0)
RETURN
END
The problem is when I look for something that does not contain endereço_B
and it returns me the last value even though it was not found. What would be the ideal way to solve this? Do I need to be resetting the variable for each condition?
Problem example:
SELECT * FROM dbo.splitSearchAddress('RUA JOÃO E MARIA', 'AVENIDA JOÃO')
It will return me
JOÃO
E
MARIA
When should I return only
JOÃO
If the substring of endereço_A
is the last position and if it is located in endereço_B
, it works correctly:
SELECT * FROM dbo.splitSearchAddress('RUA MARIA JOÃO', 'AVENIDA JOÃO')