借助CLR,首先实现字符串的互转
?
?
public
class
JsonFunction
{
///
<summary>
///
XML转JSON
///
</summary>
///
<param
name="xml"></param>
///
<returns></returns>
///
<remarks>
///
json不建议太长
///
</remarks>
[Microsoft.SqlServer.Server.SqlFunction(Name = "Xml2Json")]
public
static
SqlString
Xml2Json(SqlXml
xml)
{
System.Xml.XmlDocument
doc=new
System.Xml.XmlDocument();
doc.LoadXml(xml.Value);
string
json= JsonConvert.SerializeXmlNode(doc, Formatting.Indented);
doc.Clone();
return
new
SqlString(json);
?
}
[Microsoft.SqlServer.Server.SqlFunction(Name = "Json2Xml")]
public
static
SqlXml
Json2Xml(string
json)
{
System.Xml.XmlDocument
doc =
JsonConvert.DeserializeXmlNode(json);
System.IO.StringWriter
sw=new
System.IO.StringWriter();
doc.WriteTo(new
System.Xml.XmlTextWriter(sw));
return
new
SqlXml(new
System.Xml.XmlTextReader(new
System.IO.StringReader( sw.ToString())));
?
}
}
?
测试语句
?
DROP
TABLE
test
?
CREATE
TABLE
TEST
(
NAME VARCHAR(5),
DATA XML
)
?
GO
?
?
INSERT
INTO
TEST
VALUES (
‘A‘, ‘<ROOT><M>AAAA</M></ROOT>‘
),
(
‘B‘, ‘<ROOT><D>00000</D></ROOT>‘
)
?
DECLARE
@X
XML
SELECT
@x
=
( SELECT *
FROM
test
FOR
XML
AUTO
,
ELEMENTS
,
ROOT
)
SELECT
@x
DECLARE
@json
NVARCHAR(MAX)
SELECT
@json
=
dbo.xml2json(@x)
SELECT
@json
SELECT
dbo.Json2Xml(@json)
?
?