切两个词之间的文本

时间:2015-02-27 06:13:22

标签: sql sql-server tsql

我只想得到这个:

000020004641,000020006307,000020001441

现在我明白了:

000020004641;1003000020006307#000020006307;1003000020001441#000020001441

在我看来,我必须在两者之间剪切文字; #这个#但我不知道怎么做。

你知道怎么做吗?

2 个答案:

答案 0 :(得分:5)

示例查询:

DECLARE @text VARCHAR(150) = '000020004641;1003000020006307#000020006307;1003000020001441#000020001441'

;WITH CTE AS
(
    --initial part
    SELECT 1 AS MyCounter, LEFT(REPLACE(@text, '#', ';'), CHARINDEX(';',REPLACE(@text, '#', ';'))-1) AS MyText, 
        RIGHT(REPLACE(@text, '#', ';'), LEN(REPLACE(@text, '#', ';')) - CHARINDEX(';',REPLACE(@text, '#', ';'))) AS Remainder
    WHERE CHARINDEX(';',REPLACE(@text, '#', ';'))>0
    --recursive part
    UNION ALL
    SELECT MyCounter +1 AS MyCounter, LEFT(Remainder, CHARINDEX(';',Remainder)-1) AS MyText, 
        RIGHT(Remainder, LEN(Remainder) - CHARINDEX(';',Remainder)) AS Remainder
    FROM CTE
    WHERE CHARINDEX(';',Remainder)>0
    UNION ALL
    SELECT MyCounter +1 AS MyCounter, Remainder AS MyText, NULL AS Remainder
    FROM CTE
    WHERE CHARINDEX(';',Remainder)=0
)
SELECT *
FROM CTE

结果:

MyCounter   MyText  Remainder
1   000020004641    1003000020006307;000020006307;1003000020001441;000020001441
2   1003000020006307    000020006307;1003000020001441;000020001441
3   000020006307    1003000020001441;000020001441
4   1003000020001441    000020001441
5   000020001441    NULL

<强> [编辑]

您是MVC开发人员。所以,我的下一个建议是使用Linq:

string aText = @"000020004641;1003000020006307#000020006307;1003000020001441#000020001441";

var qry = aText.Split(new char[]{';','#'}).Select(x=>x);

干杯
马切伊

答案 1 :(得分:5)

您可以使用字符串值

000020004641;1003000020006307#000020006307;1003000020001441#000020001441

并将分隔符替换为带有开始标记和结束标记的分隔符

,将其更改为XML
000020004641<X>1003000020006307</X>000020006307<X>1003000020001441</X>000020001441

这是一个混合内容XML片段,其中您正在查找的节点值位于根级别的单独文本节点上。

然后你可以在文本节点上粉碎XML并使用for xml path技巧连接到一个字符串。

declare @S varchar(100) = '000020004641;1003000020006307#000020006307;1003000020001441#000020001441';

set @S = replace(@S, ';', '<X>');
set @S = replace(@S, '#', '</X>');

declare @X xml = cast(@S as xml);

select stuff((
            select ','+T.X.value('.', 'varchar(100)')
            from @X.nodes('text()') as T(X)
            for xml path('')
            ), 1, 1, '');

Data Explorer