用sql中的varchar变量替换“with”e

时间:2014-04-14 09:35:13

标签: sql sql-server tsql

我试图用"替换&quotreplace(@variable,'"','"')没有帮助,我用XML获取

<tag>&amp quot;Test&amp quot;</tag> 

而不是

<tag>&quot;test&quot;</tag>

示例:

DECLARE @Text varchar(20) = '"Test"'
SET @Text = REPLACE(@Text,'"','&quot ;')
SELECT @Text
DECLARE @Table table (ID int)
INSERT INTO @Table
    (ID)
VALUES
    (123)
DECLARE @TestXml AS XML = ( 
    SELECT
        @Text
    FROM @Table AS tag  
    FOR XML AUTO, ELEMENTS
    )   
SELECT @TestXml

提前致谢

1 个答案:

答案 0 :(得分:0)

如果问题出在select查询中,请尝试以下sql

更改

SELECT @TestXml

SELECT '<tag>' + @TestXml.value('/tag[1]','varchar(max)') + '</tag>'  as 'Word'

您将在选择查询中获得以下结果:

Word
-------------------------------
<tag>&quot;Test&quot;</tag>

<强>更新

保持'&amp;' char我们需要&lt;![CDATA [...]&gt; 尝试下面的sql

Declare @text nvarchar(20) = '"Test"'
select @text = replace(@text,'"','&quot;')
Declare @table table (ID int)
Declare @xml as nvarchar(Max)

insert into @table values (123)

set @xml=( Select 
    1 as tag,
    Null as Parent,
    @text as [tag!1!!CDATA]
from @table 
for xml Explicit
)

select @xml

结果:

result
---------------------------------------
<tag><![CDATA[&quot;Test&quot;]]></tag>