我创建了一个返回一些值的函数,并使用STUFF将它们全部放在一列中。
部分结果包含:
Something, something else, ?<?xml version="1.0" ... and lots of stuff in here. />
我想弄清楚的是如何删除整个:
<?xml /> tag and all of its inner content.
问题是,有时它会以每行/每行的结果的不同部分结束。
所以我尝试过CHARINDEX,LEFT,Splits ......
有什么想法吗?
谢谢。
答案 0 :(得分:1)
DECLARE @string varchar(MAX) = 'Something, something else, ?<?xml version="1.0" ... and lots of stuff in here. />, something else yet'
DECLARE @StartOfXml INT = PATINDEX('%<?xml%', @string)
DECLARE @EndOfXml INT = PATINDEX('%/>%', @string)
SELECT
SUBSTRING(@string, 0, @StartOfXml) +
SUBSTRING(@string, @EndOfXml + 2, LEN(@string))
或者把它全部内联:
DECLARE @string varchar(MAX) = 'Something, something else, ?<?xml version="1.0" ... and lots of stuff in here. />, something else yet'
SELECT
SUBSTRING(@string, 0, PATINDEX('%<?xml%', @string)) +
SUBSTRING(@string, PATINDEX('%/>%', @string) + 2, LEN(@string))
到目前为止,这个或其他答案的问题在于,根据您的XML,您可以拥有多个&#34; /&gt;&#34;在字符串中。在这种情况下,您可以执行以下操作:
DECLARE @string varchar(MAX) = 'Something, something else, ?<?xml version="1.0" ... and lots of stuff in here. />, something else yet'
SELECT SUBSTRING(@string, 0, PATINDEX('%<?xml%', @string)) +
SUBSTRING(@string, (LEN(@string) - PATINDEX('%>/%', REVERSE(@string))) + 2, LEN(@string))
最后一个解决方案假设XML的最终结束标记是字符串的最后一次出现:&#34; /&gt;&#34;。希望其中一个有所帮助!
答案 1 :(得分:0)
DECLARE @String NVARCHAR(1000)
SET @String = 'Something, something else, ?<?xml version="1.0" ......... />'
SELECT LEFT(@String,CHARINDEX('<?xml',@String)-1) Val
结果:
╔══════════════════════════════╗
║ Val ║
╠══════════════════════════════╣
║ Something, something else, ? ║
╚══════════════════════════════╝
<强>更新强>
嗯,新要求很棘手,真正困难的部分就是建立XML标签的确切位置。假设一个非常简单的场景,只存在一个XML标记,并且字符串中没有先前的/>
,那么你可以这样做:
DECLARE @String NVARCHAR(1000)
SET @String = 'Something, something else, ?<?xml version="1.0" ......... /> hello'
SELECT STUFF(@String,CHARINDEX('<?xml',@String),CHARINDEX('/>',@String)-CHARINDEX('<?xml',@String)+2,'') Val
结果:
╔════════════════════════════════════╗
║ Val ║
╠════════════════════════════════════╣
║ Something, something else, ? hello ║
╚════════════════════════════════════╝