问题描述
我想联接2个表,但是它们之间没有联接表...我通常使用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 Server中,这与cross apply
无关。然后,您可以将department
表引入常规联接:
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
id | p_name | d_name -: | :----- | :----- 1 | toto | dep10 1 | toto | dep11 1 | toto | dep12 2 | tata | dep9