4
I’m creating a function in which I will check whether a endereço_A contains parts in a endereço_B, exemplifying:
address_A
AVENIDA JOÃO E MARIA
address_B
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 in endereço_B and it returns me the last value even if it is not found,. What would be the ideal way to solve this? It will be necessary to keep redefining the variable for each same condition?
Example of the Problem:
SELECT * FROM dbo.splitSearchAddress('RUA JOÃO E MARIA', 'AVENIDA JOÃO')
He will return to me
JOÃO
E
MARIA
When I should return only
JOÃO
If the substring of endereço_A is the last position and is located in the endereço_B, works properly:
SELECT * FROM dbo.splitSearchAddress('RUA MARIA JOÃO', 'AVENIDA JOÃO')
