Monday, February 2, 2015

Replace a char with a string dynamically


declare @a table(col1 varchar(max))
insert into @a select
'DDDDDDDDDDDDDDDDDDDDDDDDDDDDXXXXXXXXXXXXXXXXXXXX
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD
DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD4444DDD'


declare @LKPTable table(col2 varchar, col3 varchar(3))
insert into @LKPTable select
'D', 'SXM'
union all select
'X', 'DSN'
union all select
'4', 'MXD'

;with staging as(
select ROW_NUMBER () over (order by (select 1)) as rn, col1, len(col1) as column_length
from @a
)

, max_row as(
select max(len(col1)) maxrow
from @a
)


, multicast_row as(
select 1 as cnt
union all
select cnt + 1
from multicast_row
where cnt < (select maxrow
from max_row)
)

, join_back as(
select cnt, SUBSTRING(col1, cnt, 1) character, staging.*, (select col3 from @LKPTable b where SUBSTRING(col1, cnt, 1) = b.col2) lookup_value
from staging, multicast_row
where len(col1) >= cnt
)

, pivot_back as(
select col1, (select cast(lookup_value as varchar(max)) from join_back b where a.col1 = b.col1 order by cnt for xml path('')) string
from staging a
)
select *
from pivot_back
OPTION (MAXRECURSION 0);


No comments:

Post a Comment