使用 string_id 连接 2 个表而不是可连接的

Join 2 tables with string_id instead of jointable

我想加入2个table但是他们之间没有加入table...我通常使用STRING_SPLIT但是在这种情况下,我无法理解出去。也许我只是累了...你能帮帮我吗?

CREATE TABLE ##Provider
(
  id INT,
  p_name VARCHAR(50),
  list_id_dep VARCHAR(250)
)

CREATE TABLE ##Department
(
  id INT,
  d_name VARCHAR(50)
)

INSERT INTO ##Provider (id, p_name, list_id_dep) VALUES 
    (1, 'toto', '/10/11/12/'),
    (2, 'tata', '/09/');

INSERT INTO ##Department (id, d_name) VALUES 
    (9, 'dep9')
    ,(10, 'dep10')
    ,(11, 'dep11')
    ,(12, 'dep12');

我想要的是:

id | p_name | d_name
--------------------------
1  | toto   | dep10
1  | toto   | dep11
1  | toto   | dep12
2  | tata   | dep09

我试过了:

select *
from ##Provider p 
inner join ##Department d on STRING_SPLIT(p.list_id_dep, '/') = ???
select *
from ##Provider p 
inner join STRING_SPLIT(p.list_id_dep, '/') dep ON dep.value = ???
select *
from ##Provider p, ##Department d
where (select value from STRING_SPLIT(p.list_id_dep, '/')) = d.id
select *
from ##Provider p, ##Department d
where d.id in (select value from STRING_SPLIT(p.list_id_dep, '/'))

也许STRING_SPLIT不是正确的做法...

谢谢!

您需要横向连接来取消嵌套字符串 - 在 SQL 服务器中,这是通过 cross apply 实现的。然后,您可以将 department table 与常规连接一起使用:

select p.id, p.p_name, d.d_name
from ##provider p 
cross apply string_split(p.list_id_dep, '/') x
inner join ##department d on d.id = x.value

Demo on DB Fiddle:

id | p_name | d_name
-: | :----- | :-----
 1 | toto   | dep10 
 1 | toto   | dep11 
 1 | toto   | dep12 
 2 | tata   | dep9