欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

实现SQL Server 原生数据从XML生成JSON数据的实例代码

程序员文章站 2022-04-09 21:49:02
实现sql server 原生数据从xml生成json数据的实例代码    sql server 是关系数据库,查询结果通常都是数据集,但是在一些特殊...

实现sql server 原生数据从xml生成json数据的实例代码

   sql server 是关系数据库,查询结果通常都是数据集,但是在一些特殊需求下,我们需要xml数据,最近这些年,json作为webapi常用的交换数据格式,那么数据库如何生成json数据呢?今天就写了一个demo.

       1.创建表及测试数据

set nocount on 
 
if object_id('stats') is not null drop table stats 
if object_id('stations') is not null drop table stations 
if object_id('operators') is not null drop table operators 
if object_id('reviews') is not null drop table reviews 
 
-- create and populate table with station 
create table stations(id integer primary key, city nvarchar(20), state char(2), lat_n real, long_w real); 
insert into stations values (13, 'phoenix', 'az', 33, 112); 
insert into stations values (44, 'denver', 'co', 40, 105); 
insert into stations values (66, 'caribou', 'me', 47, 68); 
 
-- create and populate table with operators 
create table operators(id integer primary key, name nvarchar(20), surname nvarchar(20)); 
insert into operators values (50, 'john "the fox"', 'brown'); 
insert into operators values (51, 'paul', 'smith'); 
insert into operators values (52, 'michael', 'williams');  
 
-- create and populate table with normalized temperature and precipitation data 
create table stats ( 
    station_id integer references stations(id), 
    month integer check (month between 1 and 12), 
    temp_f real check (temp_f between -80 and 150), 
    rain_i real check (rain_i between 0 and 100), primary key (station_id, month)); 
insert into stats values (13, 1, 57.4, 0.31); 
insert into stats values (13, 7, 91.7, 5.15); 
insert into stats values (44, 1, 27.3, 0.18); 
insert into stats values (44, 7, 74.8, 2.11); 
insert into stats values (66, 1, 6.7, 2.10); 
insert into stats values (66, 7, 65.8, 4.52); 
 
-- create and populate table with review 
create table reviews(station_id integer,stat_month integer,operator_id integer)  
insert into reviews values (13,1,50) 
insert into reviews values (13,7,50) 
insert into reviews values (44,7,51) 
insert into reviews values (44,7,52) 
insert into reviews values (44,7,50) 
insert into reviews values (66,1,51) 
insert into reviews values (66,7,51) 

2.查询结果集

select   stations.id    as id, 
      stations.city   as city, 
      stations.state  as state, 
      stations.lat_n  as latn, 
      stations.long_w  as longw, 
      stats.month    as month, 
      stats.rain_i   as rain, 
      stats.temp_f   as temp, 
    operators.name  as name, 
    operators.surname as surname 
from    stations  
inner join stats   on stats.station_id=stations.id  
left join reviews  on reviews.station_id=stations.id  
           and reviews.stat_month=stats.[month] 
left join operators on operators.id=reviews.operator_id 

结果:

实现SQL Server 原生数据从XML生成JSON数据的实例代码

2.查询xml数据

select stations.*, 
    (select stats.*,  
        (select operators.*  
        from  operators  
        inner join reviews on operators.id=reviews.operator_id  
        where reviews.station_id=stats.station_id  
        and  reviews.stat_month=stats.month  
        for xml path('operator'),type 
        ) operators 
    from stats  
    where stats.station_id=stations.id  
    for xml path('stat'),type 
    ) stats  
from  stations  
for  xml path('station'),type 

结果:

<station> 
 <id>13</id> 
 <city>phoenix</city> 
 <state>az</state> 
 <lat_n>3.3000000e+001</lat_n> 
 <long_w>1.1200000e+002</long_w> 
 <stats> 
  <stat> 
   <station_id>13</station_id> 
   <month>1</month> 
   <temp_f>5.7400002e+001</temp_f> 
   <rain_i>3.1000000e-001</rain_i> 
   <operators> 
    <operator> 
     <id>50</id> 
     <name>john "the fox"</name> 
     <surname>brown</surname> 
    </operator> 
   </operators> 
  </stat> 
  <stat> 
   <station_id>13</station_id> 
   <month>7</month> 
   <temp_f>9.1699997e+001</temp_f> 
   <rain_i>5.1500001e+000</rain_i> 
   <operators> 
    <operator> 
     <id>50</id> 
     <name>john "the fox"</name> 
     <surname>brown</surname> 
    </operator> 
   </operators> 
  </stat> 
 </stats> 
</station> 
<station> 
 <id>44</id> 
 <city>denver</city> 
 <state>co</state> 
 <lat_n>4.0000000e+001</lat_n> 
 <long_w>1.0500000e+002</long_w> 
 <stats> 
  <stat> 
   <station_id>44</station_id> 
   <month>1</month> 
   <temp_f>2.7299999e+001</temp_f> 
   <rain_i>1.8000001e-001</rain_i> 
  </stat> 
  <stat> 
   <station_id>44</station_id> 
   <month>7</month> 
   <temp_f>7.4800003e+001</temp_f> 
   <rain_i>2.1099999e+000</rain_i> 
   <operators> 
    <operator> 
     <id>51</id> 
     <name>paul</name> 
     <surname>smith</surname> 
    </operator> 
    <operator> 
     <id>52</id> 
     <name>michael</name> 
     <surname>williams</surname> 
    </operator> 
    <operator> 
     <id>50</id> 
     <name>john "the fox"</name> 
     <surname>brown</surname> 
    </operator> 
   </operators> 
  </stat> 
 </stats> 
</station> 
<station> 
 <id>66</id> 
 <city>caribou</city> 
 <state>me</state> 
 <lat_n>4.7000000e+001</lat_n> 
 <long_w>6.8000000e+001</long_w> 
 <stats> 
  <stat> 
   <station_id>66</station_id> 
   <month>1</month> 
   <temp_f>6.6999998e+000</temp_f> 
   <rain_i>2.0999999e+000</rain_i> 
   <operators> 
    <operator> 
     <id>51</id> 
     <name>paul</name> 
     <surname>smith</surname> 
    </operator> 
   </operators> 
  </stat> 
  <stat> 
   <station_id>66</station_id> 
   <month>7</month> 
   <temp_f>6.5800003e+001</temp_f> 
   <rain_i>4.5200000e+000</rain_i> 
   <operators> 
    <operator> 
     <id>51</id> 
     <name>paul</name> 
     <surname>smith</surname> 
    </operator> 
   </operators> 
  </stat> 
 </stats> 
</station> 

3.如何生成json数据

1)创建辅助函数

create function [dbo].[qfn_xmltojson](@xmldata xml) 
returns nvarchar(max) 
as 
begin 
 declare @m nvarchar(max) 
 select @m='['+stuff 
 ( 
   (select theline from 
  (select ','+' {'+stuff 
    ( 
       (select ',"'+coalesce(b.c.value('local-name(.)', 'nvarchar(255)'),'')+'":'+ 
           case when b.c.value('count(*)','int')=0  
           then dbo.[qfn_jsonescape](b.c.value('text()[1]','nvarchar(max)')) 
           else dbo.qfn_xmltojson(b.c.query('*')) 
           end 
         from x.a.nodes('*') b(c)                                 
         for xml path(''),type).value('(./text())[1]','nvarchar(max)') 
        ,1,1,'')+'}' 
     from @xmldata.nodes('/*') x(a) 
    ) json(theline) 
    for xml path(''),type).value('.','nvarchar(max)') 
   ,1,1,'')+']' 
  return @m 
end 

create function [dbo].[qfn_jsonescape](@value nvarchar(max) ) 
returns nvarchar(max) 
as begin 
  
 if (@value is null) return 'null' 
 if (try_parse( @value as float) is not null) return @value 
 
 set @value=replace(@value,'\','\\') 
 set @value=replace(@value,'"','\"') 
 
 return '"'+@value+'"' 
end 

3)查询sql

select dbo.qfn_xmltojson 
( 
 ( 
  select stations.id,stations.city,stations.state,stations.lat_n,stations.long_w , 
     (select stats.*,  
          (select operators.*  
          from  operators inner join reviews  
          on   operators.id=reviews.operator_id 
          where reviews.station_id=stats.station_id  
          and  reviews.stat_month=stats.month  
          for xml path('operator'),type 
          ) operators 
      from stats  
      where stats.station_id=stations.id for xml path('stat'),type 
     ) stats  
   from stations for xml path('stations'),type 
  ) 
) 

结果:

[ {"id":13,"city":"phoenix","state":"az","lat_n":3.3000000e+001,"long_w"
:1.1200000e+002,"stats":[ {"station_id":13,"month":1,"temp_f":5.7400002e+001,"
rain_i":3.1000000e-001,"operators":[ {"id":50,"name":"john \"the fox\"","surname":"brown"}]},
 {"station_id":13,"month":7,"temp_f":9.1699997e+001,"rain_i":5.1500001e+000,"operators":
[ {"id":50,"name":"john \"the fox\"","surname":"brown"}]}]}, {"id":44,"city":"denver",
"state":"co","lat_n":4.0000000e+001,"long_w":1.0500000e+002,"stats":[ {"station_id":44,
"month":1,"temp_f":2.7299999e+001,"rain_i":1.8000001e-001}, {"station_id":44,"month":7,
"temp_f":7.4800003e+001,"rain_i":2.1099999e+000,"operators":[ {"id":51,"name":"paul",
"surname":"smith"}, {"id":52,"name":"michael","surname":"williams"}, {"id":50,"name"
:"john \"the fox\"","surname":"brown"}]}]}, {"id":66,"city":"caribou","state":"me","lat_n":
4.7000000e+001,"long_w":6.8000000e+001,"stats":[ {"station_id":66,"month":1,"temp
_f":6.6999998e+000,"rain_i":2.0999999e+000,"operators":[ {"id":51,"name":"paul","
surname":"smith"}]}, {"station_id":66,"month":7,"temp_f":6.5800003e+001,"rain_i":
4.5200000e+000,"operators":[ {"id":51,"name":"paul","surname":"smith"}]}]}] 

总结:

json作为灵活的web通信交换架构,如果把配置数据存放在数据库中,直接获取json,那配置就会非常简单了,也能够大量减轻应用服务器的压力!

感谢阅读,希望能帮助到大家,谢谢大家对本站的支持!