0

I'm trying to break a string on the basis of words or characters of not same length. I'm using SQL Server 2014 Management Studio.

String ===> 'term1 OR term2'

So I want ti break it based on 'OR' so the result would be

term1
term2

It can also be like this

term3 AND term4

So it would bebroken on the basis of AND giving us the result

term3
term4
4
  • 2
    Standard single char delimiter string splitting function can be used with space delimiter and you simply ignore returned rows where value is 'OR' and 'AND'. Commented Jul 23, 2020 at 12:27
  • 1
    But perhaps you have over-simplified your sample data? Commented Jul 23, 2020 at 12:28
  • If I'm using SQL Server 2014 Management Studio means that OP uses SQL Server 2014, then STRING_SPLIT() is not available. Commented Jul 23, 2020 at 12:48
  • String splitting in sql server is discussed every day. It matters not which version of sql server OP is using - somewhere someone has posted a function to do that for versions prior to the native tsql function as well as versions that support more than just a single character delimiter. Commented Jul 23, 2020 at 13:17

2 Answers 2

7

One method is to use string_split() -- with a twist because it does not support multi-character separators:

select *
from string_split( replace(@str, ' OR ', '|'), '|')

Note: This assumes that | is not a valid "word" character.

Here is a db<>fiddle.

Sign up to request clarification or add additional context in comments.

Comments

0

Well if the extent of your use cases are splitting inputs with single OR or AND, then the base string functions can handle this:

SELECT LEFT(col, CHARINDEX(' OR ', col) - 1) AS term FROM yourTable
UNION ALL
SELECT SUBSTRING(col, CHARINDEX(' OR ', col) + 4, LEN(col)) FROM yourTable;

Data:

WITH yourTable AS (
    SELECT 'term1 OR term2' AS col
)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.