Last active
December 31, 2015 20:59
-
-
Save MyITGuy/8044261 to your computer and use it in GitHub Desktop.
SQL: Split string using XML
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
-- Splits a forward-slash delimited value using XML node names | |
-- COMPANY/COUNTRY/STATE_ABBR/CITY/OFFICE/BUILDING_CODE/NETWORK_TYPE | |
-- 1. Replace the forward-slash with the end tag and beginning of next tag '/><' | |
-- 2. Replace any space characters with an underscore character (Node names cannot contain spaces) | |
-- 3. Add tag start '<' to value | |
-- 4. Add tag end '/>' to value | |
-- 5. Cast value as XML | |
-- 6. Query XML for all node names, returning the 6th value (BUILDING_CODE) | |
-- 6. Case XML.query as VARCHAR | |
DECLARE @value VARCHAR(MAX) | |
SET @value = 'COMPANY/COUNTRY/STATE_ABBR/CITY/OFFICE/BUILDING_CODE/NETWORK_TYPE' | |
REPLACE(CAST(CAST('<' + REPLACE(REPLACE(@value, '/', '/><'), ' ', 'AAAAAA') + '/>' AS XML).query('local-name((//*)[6])') AS VARCHAR(MAX)), 'AAAAAA', ' ') |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment