Sql server 字符串用另一个表中的数据替换列数据

Sql server 字符串用另一个表中的数据替换列数据,sql-server,Sql Server,我有两张桌子: 表a: ID Values --------------- 1 Q 2 B 3 TA 4 BS TableB: RawValue Value ------------------ [1][4] QBS [2][1][3] BQTA 我需要用给定的rawValue生成TableB值。rawvalue中的每个[X]都是TableA的ID coulmn,应该用它的值替换 [1] [4]

我有两张桌子:

表a:

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

TableB:

RawValue    Value
------------------
[1][4]      QBS
[2][1][3]   BQTA
我需要用给定的rawValue生成TableB值。rawvalue中的每个[X]都是TableA的ID coulmn,应该用它的值替换

[1] [4]表示ID为1 Q的表A的值和ID为4 BS的表A的值应等于QBS

有人能建议一种方法吗

这是我已经尝试过的:

    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))) 
顺便说一下:这仍在测试过程中,如果有人有更好的想法,我可以完全更改表、行值格式和替换方法

将RawValue转换为XML,分解XML,为RawValue中的每个值获取一行,并连接到TableA以获取值

使用for xml路径技巧连接表A中的值


另外,我建议不要将字段命名为类似于保留关键字的名称,我的意思是值。

非常感谢,它就像一个符咒。虽然我一点也不懂代码是如何工作的。
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('')
            )
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