<转换为<在sql server中

时间:2012-09-12 06:57:10

标签: sql-server-2008

我的表格中有一些数据

当我使用此查询选择数据时

select TblActionHistories.Comments from TblActionHistories WHERE TblActionHistories.Entity=CAST('Task' AS VARCHAR) AND EntityId=CAST(32 AS VARCHAR)

这样就好了

Task- <b>T1</b> has been added by Swapnil Sharma
Task- <b>T1</b> status changed to <b>In Progress</b> by Swapnil Sharma<br/>

但现在我希望我的上述结果#使用stuff分隔,所以我正在使用此

SELECT STUFF((SELECT '#' + ISNULL(CAST(TblActionHistories.Comments AS VARCHAR(MAX)),'') FROM TblActionHistories WHERE TblActionHistories.Entity=CAST('Task' AS VARCHAR) AND EntityId=CAST(32 AS VARCHAR) for xml path ('')),1,1,'')

它给了我这个

Task- &lt;b&gt;T1&lt;/b&gt; has been added by Swapnil Sharma#Task- &lt;b&gt;T1&lt;/b&gt; status changed to &lt;b&gt;In Progress&lt;/b&gt; by Swapnil Sharma&lt;br/&gt;
你可以清楚地看到所有的特殊字符。喜欢&lt; &GT;分别转换为&lt; &gt;

请帮助我,我希望他们以原始格式出现

2 个答案:

答案 0 :(得分:4)

我找到了IvanG建议的解决方案

SELECT STUFF((SELECT '#' + ISNULL(CAST(TblActionHistories.Comments AS VARCHAR(MAX)),'') FROM TblActionHistories WHERE TblActionHistories.Entity=CAST('Task' AS VARCHAR) AND EntityId=CAST(32 AS VARCHAR) for xml path(''), root('MyString'), type ).value('/MyString[1]','varchar(max)') ,1,1,'')

REF。到这篇文章

http://blogs.lobsterpot.com.au/2010/04/15/handling-special-characters-with-for-xml-path/

答案 1 :(得分:-2)

尝试转换为NVARCHAR而不是VARCHAR

SELECT STUFF((SELECT '#' + ISNULL(CAST(TblActionHistories.Comments AS NVARCHAR(MAX)),'') FROM TblActionHistories WHERE TblActionHistories.Entity=CAST('Task' AS NVARCHAR) AND EntityId=CAST(32 AS VARCHAR) for xml path ('')),1,1,'')