如果您的 HTML 值总是相同的格式,请尝试以下脚本一起使用:
- 将 HTML 转换为支持的格式以使用
value () 和 node() 进行查询
Declare @x nvarchar (4000) = '<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <style type="text/css">p {font-family: sans-serif;font-size: 8.25pt;margin: 0px;}</style> </head> <body> <p>VALUE I WANT TO GET </p> </body> </html>'
select @x = replace (@x,
'<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> ',
''
);
SELECT @x = REPLACE(@x, 'xmlns=', 'xmlns:i=');
--Print @x;
- 转换后的 XML 的实际选择查询
select xmldata,
Cast (x2.c.query('data(body/p)') as nvarchar (100)) as HtmlBody
From
(select convert (xml, @x ) as xmldata) as x
cross apply xmldata.nodes('html') as x2(c)
补充:
查询直接表,如果您将@temp相应地替换为您的表名和列名,希望这会起作用
Declare @Temp table (ID bigint, xmlvalue nvarchar(4000) );
Declare @x nvarchar (4000) = '<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <title></title> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <style type="text/css">p {font-family: sans-serif;font-size: 8.25pt;margin: 0px;}</style> </head> <body> <p>VALUE I WANT TO GET </p> </body> </html>';
Insert into @Temp
VALUES (101, @x);
select x.*,
Cast (x2.c.query('data(body/p)') as nvarchar (100)) as HtmlBody
From (
select ID, CAST(REPLACE(
(replace (xmlvalue,
'<?xml version="1.0" encoding="utf-8"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> ',
'') ),
'xmlns=',
'xmlns:i='
) AS xml) as xmldata
from @Temp
) as x
CROSS APPLY xmldata.nodes('html') as x2(c)
go
如果您认为将来难以管理,请创建具有相同逻辑的标量函数 - 使用 custom scalar functions 时考虑性能方面的建议