If I do
Declare @t table(Email xml)
Declare @email varchar(100) = 'xxx&xx@monop.com'
Insert into @t
select '<Emails> <Email>' + @email +'</Email></Emails>'
select * From @t
I will get expected error
Msg 9411, Level 16, State 1, Line 8
XML parsing: line 1, character 27, semicolon expected
One solution which I found almost everywhere(including SO) is to replace '&' with '& and it works
Insert into @t
select CAST('<Emails><Email>' + REPLACE(@email, '&', '&') + '</Email></Emails>' AS XML)
Output
<Emails><Email>xxx&xx@monop.com</Email></Emails>
However, I was trying with CData approach (just another way to approach the problem)
Declare @t table(Email xml)
Declare @email varchar(100) = 'xxx&xx@monop.com'
Insert into @t
Select CAST('<![CDATA[Emails> <Email>' + @email + '</Email> </Emails]]>' AS XML)
select * From @t
When I got the below output
Emails> <Email>xxx&xx@monop.com</Email> </Emails
What I am trying to achieve is to store the data as it is i.e. the desired output should be
<Emails><Email>xxx&xx@monop.com</Email></Emails>
Is it at all possible?
I know that the replace function will fail if any other special character that xml fails to understand will be passed as an input to it e.g. ‘<‘ i which case again we need to replace it…
Thanks
Tags are PCDATA, not CDATA, so don’t put them in the CDATA section.