Reputation: 3271
I'm trying to select a value from a xml column field with the following query:
SELECT LTRIM(LocalData.value('(/root/questionphrase[@ln="nl"]/xhtml/p)[1]', 'nvarchar(max)'))
FROM Question
The structure of my xml:
<root>
<questionphrase ln="nl">
<xhtml>
<p>
Data I want to select</p>
</xhtml>
</questionphrase>
</root>
I'm getting back the expected values but they all start with 2 whitespaces. After some investigating it turns out there's a tab char(9)
and a line feed character char(10)
at the beginning of the string. Is there a generic way to strip these characters from the output without manually replacing them? I was hoping LTRIM and RTRIM would do the trick, but no luck so far.
Note: I only want to replace the characters in the beginning and the end of the string
Upvotes: 3
Views: 2006
Reputation: 2433
You can try to build a CLR function, that takes the string value as a parameter.
Then just do what you want with it in c#, and return the correct trimmed value, something like this:
[Microsoft.SqlServer.Server.SqlFunction(DataAccess=DataAccessKind.None)]
[return: SqlFacet(MaxSize = -1)]
public static SqlString TrimValue([SqlFacet(MaxSize = -1)] SqlString value) {
if(value.IsNull || value.Value.Length == 0) return value;
string trimmedValue = value.Trim();
return new SqlString(trimmedValue);
}
Upvotes: 2
Reputation: 27427
You can create separate trim functions:
Trim Functions:
CREATE FUNCTION dbo.LTrimE(@str VARCHAR(MAX)) RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE @trimchars VARCHAR(10)
SET @trimchars = CHAR(9)+CHAR(10)+CHAR(13)+CHAR(32)
IF @str LIKE '[' + @trimchars + ']%' SET @str = SUBSTRING(@str, PATINDEX('%[^' + @trimchars + ']%', @str), 8000)
RETURN @str
END
GO
CREATE FUNCTION dbo.RTrimE(@str VARCHAR(MAX)) RETURNS VARCHAR(MAX)
AS
BEGIN
DECLARE @trimchars VARCHAR(10)
SET @trimchars = CHAR(9)+CHAR(10)+CHAR(13)+CHAR(32)
IF @str LIKE '%[' + @trimchars + ']'
SET @str = REVERSE(dbo.LTrimX(REVERSE(@str)))
RETURN @str
END
GO
CREATE FUNCTION dbo.TrimE(@str VARCHAR(MAX)) RETURNS VARCHAR(MAX)
AS
BEGIN
RETURN dbo.LTrimE(dbo.RTrimE(@str))
END
GO
Your query will then look like
SELECT dbo.TRIME(LocalData.value('(/root/questionphrase[@ln="nl"]/xhtml/p)[1]',
'nvarchar(max)'))
FROM Question
Original Source for Trim functions
Upvotes: 2