如何在SQL Server 2017中使用XQuery移除XML元素中反斜杠前的字符串
How to Remove Text Before Backslash in
<GroupUserName> Elements Using XQuery in SQL Server 2017 Got it, let's fix this the right way. Treating XML as a plain string for replacements is risky—you might break the XML structure if the format changes, and it won't scale to different prefixes (like both WERD\ and NTKD0\ in your example). Instead, we'll use XQuery to target exactly the <GroupUserName> nodes and modify their text values.
First: Test the Transformation with a Query
If you want to preview the modified XML first, use this SELECT statement:
SELECT XmlDescription.query(' element Policies { for $policy in /Policies/Policy return element Policy { -- Keep all existing nodes except GroupUserName $policy/*[local-name() != "GroupUserName"], -- Recreate GroupUserName with cleaned text element GroupUserName { replace($policy/GroupUserName/text(), "^.*\\", "") } } } ') AS ModifiedXml FROM dbo.xml_temp;
Then: Update the Table with the Cleaned XML
Once you're happy with the preview, run this UPDATE to persist the changes:
UPDATE dbo.xml_temp SET XmlDescription = XmlDescription.query(' element Policies { for $policy in /Policies/Policy return element Policy { $policy/*[local-name() != "GroupUserName"], element GroupUserName { replace($policy/GroupUserName/text(), "^.*\\", "") } } } ');
How This Works
Let's break down the XQuery logic:
- Reconstruct the XML structure: We build a new
<Policies>element to preserve the original hierarchy. - Loop through each
<Policy>: For every policy node, we first copy all child nodes except<GroupUserName>(so other data like<GroupUserId>and<Roles>stays intact). - Clean the
<GroupUserName>text: Thereplace()function uses a regular expression (^.*\\) to match everything from the start of the string up to (and including) the last backslash. We replace that match with an empty string, leaving only the part after the backslash.- Note: In XQuery, backslashes in regex need to be escaped with another backslash (
\\)—that's why it's not just^.*\.
- Note: In XQuery, backslashes in regex need to be escaped with another backslash (
Why Your Previous Methods Didn't Work
- String-based REPLACE: Your first approach hardcoded
WERD\, which won't work for other prefixes likeNTKD0\. Converting XML to a VARCHAR also risks truncating data if your XML is longer than 8000 characters. - SQL REPLACE with regex: SQL Server's built-in
REPLACE()function doesn't support regular expressions—only exact string matches. That's whyreplace(CAST(XmlDescription AS VARCHAR(8000)), '^.*\', '')did nothing.
This XQuery method is robust, handles all prefixes automatically, and preserves your XML structure perfectly.
内容的提问来源于stack exchange,提问作者raoh
相关产品推荐
相关产品推荐

