Skip to content
Advertisement

Error Handling for numbers of delimiters when extracting substrings

Situation: I have a column where each cell can have up to 5 delimiters. However, it’s possible that there are none.

Objective: How do i handle errors such as :

Invalid length parameter passed to the LEFT or SUBSTRING function.

in the case that it cannot find the specified delimiter.

Query:

In this case my variable includes 5 delimiters and so my query works but if i removed one ‘-‘ it would break.

Advertisement

Answer

XML support in SQL Server brings about some unintentional but useful tricks. Converting this string to XML allows for some parsing that is far less messy than native string handling, which is very far from awesome.

For a table it’s almost identical:

Results (sorry about the massive size, seems this doesn’t handle 144dpi well):

enter image description here

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement