简体   繁体   English

T-SQL Extract部分xml或nvarchar(max)列匹配模式

[英]T-SQL Extract portion of xml or nvarchar(max) column matching pattern

I'd like to do something that I think is fairly trivial using T-SQL//SQL Server 2008 R2, but I can't seem to figure out a way. 我想做一些我认为使用T-SQL // SQL Server 2008 R2相当微不足道的事情,但我似乎无法找到方法。

If I were in Java, C#, C++, whatever, I would do: 如果我使用Java,C#,C ++,无论如何,我会这样做:

  1. Find position of first occurrance of '123' in string 在字符串中查找“123”的第一个出现位置
  2. Execute substring operation from that position getting next 50 characters 从该位置执行子串操作,获得接下来的50个字符

So, in SQL Server, I'd basically like: 所以,在SQL Server中,我基本上喜欢:

  1. Find all rows where column (X) contains said string (basically a LIKE clause) 查找列(X)包含所述字符串的所有行(基本上是LIKE子句)
  2. Return 50 characters from that column starting at the said string's location. 从所述字符串的位置开始,从该列返回50个字符。

Can I do this somehow? 我能以某种方式这样做吗? I can cast an XML column to nvarchar(max), do a like operation, and do a substring operation, I don't know how to get the position of the said string in the column in the first place though. 我可以将XML列转换为nvarchar(max),执行类似操作,并执行子字符串操作,但我不知道如何在列中首先获取所述字符串的位置。


Sample content requested in comment 评论中要求的示例内容

CREATE TABLE SampleTable(xmlData xml);

Pretend the value is in one if SampleTable's xmlData column is as follows. 如果SampleTable的xmlData列如下,则假设值为1。 I would like to, for debugging purposes, extract the string from the funny unicode Þ character forward 50 characters (or to the end of the file if that's less than 50). 我想,为了调试目的,从有趣的Þ字符前进50个字符中提取字符串(如果小于50,则提取到文件的末尾)。

<RootNode>
    <Row>
        <NestedNode1>
            some text.
        </NestedNode1>

        <NestedNode2>
            123456
        </NestedNode2>

        <NestedNode3>
            Þ Some crazy name with unicode letters. Þ
        </NestedNode3>
    </Row>
</RootNode>

Are you looking for CHARINDEX? 你在寻找CHARINDEX吗?

;WITH CTE AS(
    SELECT CAST (xmlData as nvarchar(max)) as X
    FROM SampleTable
)
SELECT SUBSTRING(X,CHARINDEX(N'Þ',X),50) as [String]
FROM CTE
WHERE CHARINDEX(N'Þ',X)>0

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM