select *
FROM (SELECT a = '<'+nchar(2)+'>') x
for xml path(''),type
对于上述 statemnet,您将收到此错误。
FOR XML 无法序列化节点“a”的数据,因为它包含 XML 中不允许的字符 (0x0002)。要使用 FOR XML 检索此数据,请将其转换为二进制、varbinary 或图像数据类型并使用 BINARY BASE64 指令。
我创建了一个 sql 函数来解决这个问题
USE master;
GO
IF (OBJECT_ID('str_to_xml') IS NOT NULL) DROP FUNCTION dbo.str_to_xml;
GO
CREATE FUNCTION dbo.str_to_xml(@input AS nvarchar(max))
RETURNS xml
BEGIN
DECLARE @i int, @iText nvarchar(100);
SET @i = 0x0;
WHILE (@i <= 0x8)
WHILE (@i <= 0xFFFF)
BEGIN
SET @iText = master.dbo.fn_varbintohexstr(@i);
SET @iText = ISNULL(STUFF(@iText, 1, PATINDEX('%[^0x]%', @iText) - 1, ''), '0');
SET @iText = '&#x' + CASE WHEN LEN(@iText) > 1 THEN '' ELSE '0' END + @iText + ';';
SET @input = REPLACE(@input, @iText, '');
SET @i = CASE
WHEN @i + 1 BETWEEN 0x9 AND 0xA THEN 0xA
WHEN @i + 1 = 0xD THEN 0xD
WHEN @i + 1 BETWEEN 0x20 AND 0xD7FF THEN 0xD7FF
WHEN @i + 1 BETWEEN 0xE000 AND 0xFFFD THEN 0xFFFD
ELSE @i + 1 END + 1;
END
RETURN CONVERT(xml, @input);
END
GO
用法:
select master.dbo.str_to_xml((select *
FROM (SELECT a = '<'+nchar(2)+'>') x
for xml path('')))