Skip to content

Instantly share code, notes, and snippets.

@MyITGuy
Last active December 31, 2015 20:59
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MyITGuy/8044261 to your computer and use it in GitHub Desktop.
Save MyITGuy/8044261 to your computer and use it in GitHub Desktop.
SQL: Split string using XML
-- 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