I needed to select rows from a database which corresponded to a note on a case. Each row was then written as xml to a file. Some of the columns in the row contained user entered information which could contain special characters which would create badly formed xml '<' and '>' for example. I needed a way to encode the column values when selected so that special characters were replaced.
The solution:
With a little help from the fellas over at StackOverflow.com I implemented a user-defined function which encoded the original column value. Performance wasn't a big concern as the query only ever returns one row, hence using a function;
ALTER FUNCTION [pega].[encodeTextForXml]
(
@string_to_encode varchar(1000)
)
RETURNS VARCHAR(MAX)
AS
BEGIN
declare @x xml
declare @encStr varchar(8000)
set @x = '<a/>'
set @x.modify('insert text{sql:variable("@string_to_encode")} as first into (/a)[1]')
set @encStr = CAST(@x.query('/a/text()') as varchar(8000))
RETURN @encStr
END
If I had the luxury of not being penned in by existing code, this would have been solved differently as suggested in the StackOverflow post, however it works well and does what it says on the tin!
No comments:
Post a Comment