问题
我正在尝试声明一个 XML 变量,并在我的 SQL 查询中将其设置为等于此DECLARE @x XML = 'xml content here';
XML 文件,如下所示:但是,当我尝试使用当前的 XML 文件执行此操作时,我会在屏幕上打印此错误消息:
Msg 9420, Level 16, State 1, Line 1
XML parsing: line 1132, character 265, illegal xml character
我已经尝试解决的方法
- 我试图通过用两个单引号替换 XML 文件中的所有单引号然后复制到查询中来转义单引号。没运气。
- 我试过取出 & 符号,但这似乎不起作用。在 SQL 检测到错误的位置附近,似乎没有任何特殊字符。又没有运气了。
问题
在我看来,单引号不是问题。我无法准确找到非法字符是什么,以及如何过滤掉这些字符。也许从外部文件导入 XML 文件并将内容设置为等于变量而不是听到编码它将解决问题。这将如何工作?我也知道单引号必须用两个单引号代替。我这样做了,但我仍然有完全相同的问题。感谢您对理解该问题的任何帮助。
系统参数
- MS SQL Server 管理工作室
- Windows Server 2012 R2 标准版
完整代码
这是我正在执行的完整代码,它给了我错误:
DECLARE @x XML = ' copy xml file here... ';
With MyPersonCTE AS
(
SELECT ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS PersonID
,p.value('FirstName[1]','varchar(max)') AS FirstName
,p.value('LastName[1]','varchar(max)') AS LastName
,p.value('Biography[1]','varchar(max)') AS Biography
,p.value('Expertise[1]','varchar(max)') AS Expertise
,p.value('Image[1]','varchar(max)') AS Image
,p.value('Link[1]','varchar(max)') AS Link
,p.query('Books') AS BookNode
,p.query('Articles') AS ArticleNode
--same for Papers, Artwork...
FROM @x.nodes('/People/Person') AS A(p)
)
,MyBooksCTE AS
(
SELECT MyPersonCTE.*
,ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS BookID
,x.value('Year[1]','int') AS BookYear
,x.value('Details[1]','varchar(max)') AS BookDetails
FROM MyPersonCTE
CROSS APPLY MyPersonCTE.BookNode.nodes('/Books/Book') A(x)
)
,MyArticlesCTE AS
(
SELECT MyPersonCTE.*
,ROW_NUMBER() OVER(ORDER BY (SELECT NULL)) AS ArticleID
,x.value('Year[1]','int') AS ArticleYear
,x.value('Details[1]','varchar(max)') AS ArticleDetails
FROM MyPersonCTE
CROSS APPLY MyPersonCTE.ArticleNode.nodes('/Articles/Article') A(x)
)
--same for Papers, Artwork...
SELECT p.*
,b.BookID
,b.BookYear
,b.BookDetails
,a.ArticleID
,a.ArticleYear
,a.ArticleDetails
INTO #tempAllData
FROM MyPersonCTE AS p
LEFT JOIN MyBooksCTE AS b ON p.PersonID=b.PersonID
LEFT JOIN MyArticlesCTE AS a ON p.PersonID=a.PersonID ;
--#tempAllData is now filled with all data, copied in all combination: much to much
--but DISTINCT is your friend
--in this case you'd use the PersonID as FK in all related tables
SELECT DISTINCT PersonID,FirstName,LastName,Biography,Expertise --other fields
FROM #tempAllData;
SELECT DISTINCT PersonID,BookID,BookYear,BookDetails
FROM #tempAllData;
SELECT DISTINCT PersonID,ArticleID,ArticleYear,ArticleDetails
FROM #tempAllData;
DROP TABLE #tempAllData;