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 the expected error
Msg 9411, Level 16, State 1, Line 8 XML parsing: Line 1, character 27, expected semicolon
One solution that I found almost everywhere (including SO) is that it replace '&' with '&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 tried to use the 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 did I get the bottom output
Emails> <Email>xxx&xx@monop.com</Email> </Emails
What I'm trying to achieve is to store the data as it is, that is, the desired result should be
<Emails><Email>xxx&xx@monop.com</Email></Emails>
Is it possible?
I know that the replace function will not work if some other special character that xml cannot understand is passed as input to it, for example. '& L;' in which case we must replace it again ...
thank
user1323981