如果您无法修复设计(您不应该将多条数据存储在单个列中,正如其他地方所指出的那样),您可以使用拆分功能来完成此操作:
CREATE FUNCTION dbo.SplitStrings
(
@List NVARCHAR(MAX),
@Delim NCHAR(1)
)
RETURNS TABLE
AS
RETURN ( SELECT DISTINCT Item FROM
( SELECT Item = x.i.value('(./text())[1]', 'nvarchar(max)')
FROM ( SELECT [XML] = CONVERT(XML, '<i>'
+ REPLACE(@List, @Delim, '</i><i>') + '</i>').query('.')
) AS a CROSS APPLY [XML].nodes('i') AS x(i) ) AS y
WHERE Item IS NOT NULL
);
GO
现在你可以说:
SELECT t1.FAQ, t2.MODELS, t2.PIC
FROM dbo.Table1 AS t1
CROSS APPLY dbo.SplitStrings(t1.MODELS, ' ') AS s
INNER JOIN dbo.Table2 AS t2
ON s.Item COLLATE SQL_Latin1_General_CP1_CI_AS
= t2.Models COLLATE SQL_Latin1_General_CP1_CI_AS
ORDER BY t1.FAQ;
结果:
FAQ MODELS PIC
---- ------ ---------
faq1 model1 model1pic
faq2 model1 model1pic
faq2 model2 model2pic
faq3 model1 model1pic
faq3 model2 model2pic
faq3 model3 modal3pic
您尝试使用的查询:
SELECT kwfaqtmp.faqmodelnum, kwFAQtmp.issue,kwfaqtmp.resolution,
kwtable4tmp.modelnum, kwtable4tmp.prodpic
FROM kwfaqtmp AS t1
CROSS APPLY dbo.SplitStrings(t1.faqmodelnum, ' ') AS s
INNER JOIN dbo.kwtable4tmp AS t2
ON s.item COLLATE SQL_Latin1_General_CP1_CI_AS
= t2.modelnum COLLATE SQL_Latin1_General_CP1_CI_AS
ORDER BY t1.issue;
根本无效。尽管它不应该产生您在评论中引用的确切错误。保持 t1 / t2 别名作为我的原始查询显示如何?
SELECT t1.faqmodelnum, t1.issue, t1.resolution,
t2.modelnum, t2.prodpic
FROM kwfaqtmp AS t1
CROSS APPLY dbo.SplitStrings(t1.faqmodelnum, ' ') AS s
INNER JOIN dbo.kwtable4tmp AS t2
ON s.item COLLATE SQL_Latin1_General_CP1_CI_AS
= t2.modelnum COLLATE SQL_Latin1_General_CP1_CI_AS
ORDER BY t1.issue;