Click here to Skip to main content
15,881,757 members
Please Sign up or sign in to vote.
1.50/5 (2 votes)
See more:
Dear Friends,

I have a string :-
'25/26*34+21'
and I want it to be converted into this

'[25]/[26]*[34]+[21]'
in SQL.

Kindly help as i am have tried a lot.

What I have tried:

I tried using CharIndex, Replace but no success.
Posted
Updated 21-Nov-18 0:20am

To be honest, you would be much better off doing this in your presentation language: SQL string handling is poor, and it's support for regular expressions is ... um ... dreadful.

If you get it working, it'll be slow and difficult to maintain, but it is possible with PATINDEX and STUFF, as this example shows: sql server - Regex pattern inside SQL Replace function? - Stack Overflow[^] - that won't do exactly what you are after, but it shoudl give you teh general idea and show you just how much work you are getting yourself into.

Seriously, do it in your presentation code: SQL is excellent at storing and relating information, but it's not designed for heavy duty string manipulation.
 
Share this answer
 
Comments
Varun Sareen 21-Nov-18 4:40am    
I agree to what you have written on this but my requirement is like this only. I am not able to come up with a solution to this. Quiet frustrated till now. Thanks for the effort.
I wholeheartedly agree with @OriginalGriff and if anyone tells you different they're wrong :laugh:

However, I note your comment that you appear to have no choice so here is an alternative approach using REPLACE
SQL
declare @Test varchar(125) = '25/26*34+21+15'

select '[' + replace(replace(replace(replace(@Test, '+',']+['), '-',']-['),'*',']*['),'/',']/[') + ']'
Points to note:
- I have only used + , - , * and / - you will have to extend the principle for any other characters you want to use
- Be sure to read the documentation at REPLACE (Transact-SQL) | Microsoft Docs[^]
- Spot the [ and ] added at either end and consider what will happen if your string begins or ends with any of the characters you are replacing
- Try to find a way to do this in your presentation layer
 
Share this answer
 
Comments
Varun Sareen 28-Jan-19 7:02am    
thanks

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900