patternsqlMinor
Replace Character Without Using Looped REPLACE Function
Viewed 0 times
withoutreplacecharacterfunctionusinglooped
Problem
My SQL Server database input values follow a pattern of where the first position is a character and then followed by number. I want replace the first character with another character or characters . For example:
input
output
Potential values for the first position are
I am looking for an option without using multiple
If I use
Please suggest any better way to do achieve the results.
input
Q234567888
R264747848
B264712481
output
I234567888
I264747848
U264712481
Potential values for the first position are
[A-Z]. I am looking for an option without using multiple
REPLACE statement and not using CASE.If I use
CASE, I will have to check 26 cases or if I use REPLACE in a nested way, I may end up using 26 REPLACE statements. I am trying to avoid these.Please suggest any better way to do achieve the results.
Solution
Create a mapping between the old value and the new value in a table value constructor and use stuff to replace the character.
declare @T table(Value varchar(10));
insert into @T values
('Q234567888'),
('R264747848'),
('B264712481');
select stuff(T.Value, 1, 1, (
select V.NewValue
from (values('Q', 'I'),
('R', 'I'),
('B', 'U')) as V(OldValue, NewValue)
where V.OldValue = left(T.Value, 1)
))
from @T as T;Code Snippets
declare @T table(Value varchar(10));
insert into @T values
('Q234567888'),
('R264747848'),
('B264712481');
select stuff(T.Value, 1, 1, (
select V.NewValue
from (values('Q', 'I'),
('R', 'I'),
('B', 'U')) as V(OldValue, NewValue)
where V.OldValue = left(T.Value, 1)
))
from @T as T;Context
StackExchange Database Administrators Q#201851, answer score: 7
Revisions (0)
No revisions yet.