SQL Server:使用查找其他表替换字段中的值

时间:2017-12-06 13:28:20

标签: sql sql-server sql-server-2008 tsql

假设我有下表脚本

private async void OnVoting(ImageVotingModel image)
        {
            if (IsBusy)// it's true when there is a work being done on server
                return;
            Images.Single(x => x.id == image.id).UpVoted = !image.UpVoted; //with data-binding, once the Upvoted change the icon is updated
           // if (!await SendVote(image))
             //   Images.Single(x => x.id == image.id).UpVoted = !image.UpVoted;

        }

输出如下: @result

DECLARE @result TABLE
   (
    [ID] Int
   ,[Data] Varchar(500)
   )
DECLARE @codes TABLE
   (
    [ID] Varchar(500)
   ,[FullNames] Varchar(500)
   )
INSERT   INTO @result
         SELECT   1
                 ,'[A]-[B]'
INSERT   INTO @result
         SELECT   2
                 ,'[D]-[A]'
INSERT   INTO @result
         SELECT   3
                 ,'[A]+[C]'

INSERT   INTO @codes
         SELECT   'A'
                 ,'10'
INSERT   INTO @codes
         SELECT   'B'
                 ,'20'
INSERT   INTO @codes
         SELECT   'C'
                 ,'30'
INSERT   INTO @codes
         SELECT   'D'
                 ,'40'

SELECT * FROM @result
SELECT * FROM @codes

@codes

ID  Data
--  -------
1   [A]-[B]
2   [D]-[A]
3   [A]+[C]

现在我想要输出如下:

ID  FullNames
--  -------
A   10
B   20
C   30
D   40

请帮帮我。 请注意:数据列还包含([A] - [B] + [D])* [C]

我在https://stackoverflow.com/a/26650255/8454103上找到了类似的解决方案,供您参考。

2 个答案:

答案 0 :(得分:0)

试试这个;

select Output from (
select Data, c1.FullNames as LeftSideName, c2.FullNames as RightSideName, LeftSide, RightSide, REPLACE(REPLACE(Data,'[' + LeftSide + ']',c1.FullNames),'[' + RightSide + ']',c2.FullNames) as Output from (
select r.ID, Data,SUBSTRING(Data, 2, 1) LeftSide ,SUBSTRING(Data, 6, 1) RightSide from @result r ) Result
inner join @codes c1 ON Result.LeftSide = c1.ID
inner join @codes c2 ON Result.RightSide = c2.ID)
Records

Output:
10-20
10+30
40-10

查询可以根据@codes表格等动态替换 A,B,C,D,E

答案 1 :(得分:0)

试试这个:

select ID, REPLACE(REPLACE(REPLACE(REPLACE(Data,
            '[A]', (select FullNames from @codes where ID = 'A')),
            '[B]', (select FullNames from @codes where ID = 'B')),
            '[C]', (select FullNames from @codes where ID = 'C')),
            '[D]', (select FullNames from @codes where ID = 'D'))
from @result