Skip to content
Advertisement

How to parse apt no from the address field in SQL [closed]

I NEED TO EXTRACT LAST NUMBER IN THE DATA AS APTNO?

[enter image description here][1]

My data in the below picture. I m almost there to get my results but i want the number and also when there is APt i want number with APT as well

Advertisement

Answer

One more method based on JSON.

It will work starting from SQL Server 2016 onwards.

SQL Server 2016

-- DDL and sample data population, start
DECLARE @tbl TABLE (ID INT IDENTITY PRIMARY KEY, tokens VARCHAR(250));  
INSERT Into @tbl (tokens) VALUES 
('250 Cambridge ST 305'),
('30 ACKERS AVE 2');
-- DDL and sample data population, end

DECLARE @Word INT = 4;
SELECT * 
    , token = JSON_VALUE('["' +
        REPLACE(REPLACE(tokens
            ,'"','"')
            ,' ','","') +
        '"]', CONCAT('$[', @Word-1,']'))
FROM @tbl ;

SQL Server 2008 onwards

XML/XQuery based method. Useful when number of tokens fluctuates (or unknown) for each row.

DECLARE @separator CHAR(1) = SPACE(1);
SELECT * 
    , TRY_CAST('<root><r><![CDATA[' + 
    REPLACE(tokens, @separator, ']]></r><r><![CDATA[') + 
    ']]></r></root>' AS XML).value('(/root/r[last()]/text())[1]', 'NVARCHAR(30)') AS token
FROM @tbl;

Output

+----+----------------------+-------+
| ID |        tokens        | token |
+----+----------------------+-------+
|  1 | 250 Cambridge ST 305 |   305 |
|  2 | 30 ACKERS AVE 2      |     2 |
+----+----------------------+-------+
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement