3

我在 Microsoft SQL 数据库中有两个表,一个包含 3 列带有分隔值的列(通过逗号和/或斜杠,但两者都应同样视为分隔符)。然后我有另一个表,其中包含一个 ID,该 ID 与 TABLE1 中拆分字符串中的每个项目相同。我想解析表 1 中的项目,以便显示表 2 中匹配行的文本。有没有办法做到这一点?

表格1

Text1           Text2           Text3
TA12,TA250      T1  
TA12,TA250      T1  
TA12,TA250      TA250,TA12      T310/T52
TA12,TA250      TA250           T310/T52

表2

TA12            Hello
TA250           World
T1              This is a Test
T310            You are
T52             a Hero

期望的结果

Text1           Text2           Text3
Hello World     This is a Test  NULL
Hello World     This is a Test  NULL
Hello World     World Hello     You are a Hero
Hello World     World           You are a Hero

我可以使用 C# 来实现这一点,但我非常希望这发生在 SQL 端。

4

1 回答 1

2

在最新版本的 SQL Server 中,您可以执行以下操作:

select t.*, t1.new_text1, t2.new_text2, t3.new_text3
from table1 t outer apply
     (select string_agg(t2.col2) as new_text1
      from table2 t2
      where t2.col1 in (select * from string_split(replace(t.text1, '/', ','), ','))
     ) t1 outer apply
     (select string_agg(t2.col2) as new_text2
      from table2 t2
      where t2.col1 in (select * from string_split(replace(t.text2, '/', ','), ','))
     ) t2 outer apply
     (select string_agg(t2.col2) as new_text3
      from table2 t2
      where t2.col1 in (select * from string_split(replace(1.text3, '/', ','), ','))
     ) t3;

也就是说,修复数据模型应该优先于尝试使用它。

于 2019-08-13T11:43:45.917 回答