Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.2k views
in Technique[技术] by (71.8m points)

sql - Variable length substring between two characters

Data looks like this:

Initiative: Credible Sources;
Initiative: Just in Time;
Initiative: Database Normalization;

I want it to look like this:

Credible Sources
Just in Time
Database Normalization

It's pretty simple to get rid of one or the other.

This:

SELECT DISTINCT LEFT(OPTIONAL_FIELD_2, CHARINDEX(';', OPTIONAL_FIELD_2 + ';')-1) AS OPTIONAL_FIELD_2
FROM my_table
ORDER BY OPTIONAL_FIELD_2

Gives me this: Initiative: Credible Sources Initiative: Just in Time Initiative: Database Normalization

And this:

SELECT DISTINCT RIGHT(OPTIONAL_FIELD_2, LEN(OPTIONAL_FIELD_2)-12) AS OPTIONAL_FIELD_2
FROM my_table
ORDER BY OPTIONAL_FIELD_2

Gives me this:

Credible Sources;
Just in Time;
Database Normalization;

Having a hard time figuring out how to combine the two.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

How about just using substring()?

select replace(substring(option_field_2, 13, 999), ';', '')

Or, if you don't know how long the prefix is:

select replace(stuff(option_field_2, 1, charindex(':', option_field_2) + 1, ''), ';', '')

Here is a db<>fiddle.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...