0

I have two tables:

TableA:

ID       Values
---------------
1         Q
2         B
3         TA
4         BS

TableB:

RawValue    Value
------------------
[1][4]      QBS
[2][1][3]   BQTA

I need to generate TableB values with its given RawValues. each [X] in rawvalue is the ID coulmn of TableA and shoud be replace with its value .

[1][4] means that Value of TableA with has ID of 1 (Q) and Value of TableA with has ID of 4 (BS) then should equal to QBS.

can anyone suggest a way to do it?

this is what I have already tried:

    update tableb set value=replace(rawvalue,'[' + (select id from tablea where id = cast(replace(replace(rawdata,'[',''),']','') as int)) + ']',
(select values from tablea where id = cast(replace(replace(rawdata,'[',''),']','') as int))) 

By the way: this is still in test process and I can totally change tables, rowvalue format and replacement methods if anyone has a better idea.

2 Answers 2

2
declare @tableA table (id int, value varchar(50))
insert into @tableA (id, value)
select 1, 'Q' union all
select 2, 'B' union all
select 3, 'TA' union all
select 4, 'BS'

declare @tableB table (rawdata varchar(255), value varchar(255))
insert into @tableB (rawdata)
select '[1][4]' union all -- QBS
select '[2][1][3]' -- BQTA


update b
set value = (
        select a.value + ''
        from @tableA a
        cross apply (select charindex ('[' + cast (a.id as varchar(50)) + ']', b.rawdata) as pos) p
        where pos > 0
        order by pos
        for xml path('')
    )
from @tableB b

select * from @tableB

P.S. I would recommend not to name field similar to reserved keywords (I mean Values).

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

1 Comment

Thanks a lot it works like a charm. although I didn't understand a bit how code works.
0

Turn RawValue into XML, shred the XML to get one row for each value in RawValue and join to TableA to get the value.

Use the for xml path() trick to concatenate the values from TableA.

update TableB
set Value = (
            select T.Value as '*'
            from (
                 select row_number() over(order by T2.X) as SortOrder,
                        TableA.Value
                 from (select cast(replace(replace(TableB.RawValue, '[', '<x>'), ']', '</x>') as xml)) as T1(X)
                   cross apply T1.X.nodes('x') as T2(X)
                   inner join TableA
                     on TableA.ID = T2.X.value('text()[1]', 'int')
                 ) as T
            order by T.SortOrder
            for xml path('')
            )

SQL Fiddle

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.