如何解析具有多个单词的字段并在不同的表中查找每个单词?

时间:2015-07-07 22:05:51

标签: sql-server sql-server-2008 string-concatenation

我有一个包含RxDirRxNum列的表DirDir由用户输入的文本组成,该文本是快速代码和自由文本的组合。快速代码存储在SCodes列下的SCode表格中。

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

LYLAS BUT OMG YOU HAVE VD & BEANS

然后我需要将结果解释为

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

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

1 个答案:

答案 0 :(得分:3)

你想要的第一件事是字符串分割器。这是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

使用上述结果,您现在可以在LEFT JOIN上执行SCodes来获取每个ExTxt的含义或Item。然后将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

<强> RESULT

| 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