Shrewdroid
Shrewdroid

Reputation: 800

Replace Ids with respective text values in a row

I have a row that provides me values like shown below:

ClubbedValues
-----------------------------------------------------
561#557, 562#558, 563#559, 561#560, 562#560
581#578, 581#579, 581#580
561#557, 562#558, 562#559, 563#560

I have a master table where I have text values against these id's. For example:

Id     TextValue
-----------------------------------------------------
561    Value1
562    Value2
563    Value3
564    Value4
565    Value5

Now I somehow desire the following output:

ClubbedValues
-----------------------------------------------------
Value1#Value107, Value2#Value108, Value3#Value109 etc..

Where both the text values are mapped somewhere in the master table.

I hope you got the question....

Any help will be appreciated.

Thank you.

Upvotes: 0

Views: 177

Answers (1)

Mikael Eriksson
Mikael Eriksson

Reputation: 138970

You can do this using a table variable and a loop over all values you would need to replace.

declare @T table(ClubbedValues varchar(max))
declare @Id int
declare @Value varchar(10)

-- Get the rows from YourTable that you need to process  
insert into @T
select ClubbedValues
from [your table]

select top 1 
  @Value = TextValue,
  @Id = Id
from [master table]
order by Id  

while @@rowcount > 0
begin
  update @T 
    set ClubbedValues = replace(ClubbedValues, cast(@Id as varchar(10)), @Value)

  select top 1 
    @Value = TextValue,
    @Id = Id
  from [master table]
  where Id > @Id
  order by Id  
end

select *
from @T

Upvotes: 1

Related Questions