如何解析包含多个词的字段并在不同的 table 中查找每个词?

How do I parse a field with multiple words and look each word up in a different table?

我有一个 table RxDir,其中包含列 RxNumDirDir 由用户输入的文本组成,该文本是快速代码和自由文本的组合。快速代码存储在 SCode.

列下名为 SCodes 的 table 中

我需要在给定 RxNum 时创建方向的扩展结果。所以如果 Dir 包含

LYLAS BUT OMG YOU HAVE VD & BEANS

然后我需要将结果解释为

LOVE YOU LIKE A SISTER BUT OH MY GOODNESS YOU HAVE VIENNA DOGS & BEANS

(假设明显的首字母存储在SCodes中,而不是完整的单词)。

您首先需要的是字符串拆分器。这是 DelimitedSplit8K,最快的分离器之一。

CREATE FUNCTION [dbo].[DelimitedSplit8K](
    @pString VARCHAR(8000), @pDelimiter CHAR(1)
)
RETURNS TABLE WITH SCHEMABINDING AS
RETURN
WITH E1(N) AS (
    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL 
    SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1 UNION ALL SELECT 1
)
,E2(N) AS (SELECT 1 FROM E1 a, E1 b)
,E4(N) AS (SELECT 1 FROM E2 a, E2 b)
,cteTally(N) AS(
    SELECT TOP (ISNULL(DATALENGTH(@pString), 0)) ROW_NUMBER() OVER (ORDER BY (SELECT NULL)) FROM E4
)
,cteStart(N1) AS(
    SELECT 1 UNION ALL 
    SELECT t.N+1 FROM cteTally t WHERE SUBSTRING(@pString, t.N, 1) = @pDelimiter
),
cteLen(N1, L1) AS(
SELECT 
    s.N1,
    ISNULL(NULLIF(CHARINDEX(@pDelimiter, @pString, s.N1),0) - s.N1, 8000)
FROM cteStart s
)
SELECT 
    ItemNumber = ROW_NUMBER() OVER(ORDER BY l.N1),
    Item       = SUBSTRING(@pString, l.N1, l.L1)
FROM cteLen l

现在,您想要的是将每个 Dir 拆分为 ' ' 作为分隔符。使用您的示例数据和上面的函数

SELECT * FROM dbo.DelimitedSplit8K('LYLAS BUT OMG YOU HAVE VD & BEANS', ' ')

结果是:

ItemNumber  Item
----------- ----------
1          LYLAS
2          BUT
3          OMG
4          YOU
5          HAVE
6          VD
7          &
8          BEANS

使用上述结果,您现在可以在 SCodes 上执行 LEFT JOIN 以获得每个 Item 的含义或 ExTxt。然后将 ExTxt 连接回去以获得所需的结果。

您的最终查询将是:

SELECT
    rd.RxNum,
    rd.Dir,
    Result = 
        STUFF((
            SELECT ' ' + ISNULL(sc.ExTxt, x.Item)
            FROM dbo.DelimitedSplit8K(rd.Dir, ' ' ) x
            LEFT JOIN SCodes sc
                ON sc.SCode = x.Item
            FOR XML PATH(''), TYPE).value('.', 'NVARCHAR(MAX)'),        
        1, 1, '')
FROM RxDir rd

结果

| RxNum |                               Dir |                                                                Result |
|-------|-----------------------------------|-----------------------------------------------------------------------|
|     1 | LYLAS BUT OMG YOU HAVE VD & BEANS | LOVE YOU LIKE A SISTER BUT OH MY GOODNESS YOU HAVE VIENA DOGS & BEANS |

注意:请参阅 Aaron Bertrand 的 article 了解其他字符串拆分器。

SQL Fiddle