由于一个 T2.Col2 可以保存n 个条目,因此您需要使用表值函数将它们解析为行,然后使用CROSS APPLY
请注意,如果 T2 很大,此解决方案将挂起很长时间
像这样的东西:
;WITH IDSplitted AS
(
SELECT *
FROM T2
CROSS APPLY dbo.[StringSplit](col2, ';')
)
SELECT * -- or whatever columns you need
FROM T1
INNER JOIN IDSplitted ON IDSplitted.val = t1.col1
有StringSplit:
CREATE FUNCTION [dbo].[StringSplit]
(
@delimited nvarchar(max),
@delimiter nvarchar(100)
) RETURNS @t TABLE
(
-- Id column can be commented out, not required for sql splitting string
id int identity(1,1), -- I use this column for numbering splitted parts
val nvarchar(max)
)
AS
BEGIN
declare @xml xml
set @xml = N'<root><r>' + replace(@delimited,@delimiter,'</r><r>') + '</r></root>'
insert into @t(val)
select
r.value('.','varchar(max)') as item
from @xml.nodes('//root/r') as records(r)
RETURN
END