0

I need to clean up a string field and replace a dozen different patterns. I know you can use a nested REPLACE function, but doing that a lot is a real pain to type and makes for some very ugly code.

Is there a more efficient way to do this?

1
  • 2
    The nested replace() is possibly the fastest approach. There are other methods, but they are probably slower for the general case. Commented Jan 27, 2016 at 20:40

2 Answers 2

3

You can do the nested replace . . . without nesting. Here is one method:

select t.*, t_r12.col_r
from t outer apply
     (select replace(t.col, 'in1', 'out1') as col_r) t_r01 outer apply
     (select replace(t_r01.col_r, 'in2', 'out2') as col_r) t_r02 outer apply
     (select replace(t_r02.col_r, 'in3', 'out3') as col_r) t_r03 outer apply
     . . .;

In this context, I don't think that outer apply adds any (significant) overhead. However, this does require naming all the intermediate results.

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

Comments

1

You could write a CLR procedure that uses a REGEX to do the replace.

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.