Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you keep HTML tags when querying a xml using sql?

I want to keep html tags in my sql query when i write a query to generate xml tags. For example:

select '<p> this is a code</p>' as code
from table name
for xml path (''), type

outputs:

<code>&ltp&gt; this is a code &lt/p&gt; <code>

what it should output:

<code><p> this is a code </p><code>

How do I solve this? Thanks!

like image 606
Bartman Avatar asked Jun 04 '12 02:06

Bartman


People also ask

How do I save HTML code in SQL database?

It is recommended to use NVARCHAR datatype for saving HTML tags (codes). Note: The SQL for creating the database is provided in the attached sample code. The following HTML Markup consists of a Multiline TextBox and is made a Rich TextBox using the TinyMCE RichTextEditor plugin and a Button.

Can we write SQL queries in HTML?

You can produce HTML from SQL because SQL Server has built-in support for outputting XML, and HTML is best understood as a slightly odd dialect of XML that imparts meaning to predefined tags. There are plenty of edge cases where an HTML structure is the most obvious way of communicating tables, lists and directories.


2 Answers

If using xhtml, I believe the conversion to Xml will do:

select convert(xml, '<p> this is a code</p>') as code
from table name
for xml path (''), type

EDIT: if the column is ntext, implicit conversion to Xml is supported:

create table #t(html ntext)
insert into #t values(N'<p> this is a code</p>')
select convert(xml, html) as code
from #t
for xml path (''), type
drop table #t
like image 187
dan radu Avatar answered Sep 28 '22 07:09

dan radu


below snippets works for me

DECLARE @HTMLt  NVARCHAR(MAX)  ;

........

SET @HTMLt = REPLACE(REPLACE(REPLACE(@HTMLt,'&amp;','&' ) , '&lt;','<'),'&gt;','>');
like image 42
Iman Avatar answered Sep 28 '22 06:09

Iman