sql-server - 将两列转换为键值 json 对象?

标签 sql-server json user-defined-functions entity-attribute-value

使用 FOR JSON AUTOFOR JSON PATH在以下记录集(代表产品的属性)上:

attribute | value
-----------------
color     | red
size      | small

将产生:
[{"attribute":"color","value":"red"},{"attribute":"size","value":"small"}]

有什么方法可以产生以下相反的结果:
{"color":"red","size":"small"}

备注 因为每个产品属性都与其他属性不同;所以这个记录集对于每个产品都是不同的。 PIVOTing 不是一个选项,因为它需要动态 sql!似乎我们需要一个函数才能CROSS它与产品表生成例如 产品目录 .

最佳答案

我没有使用 SQL Server 2016 的 JSON 函数,而是使用了 string concatenation function string_agg in SQL Server 2017如以下脚本所示

/*create table ProductAttributes (
    product int,
    attribute varchar(40),
    value varchar(40)
)
insert into ProductAttributes select 1, 'color', 'red'
insert into ProductAttributes select 1, 'size', 'small'
insert into ProductAttributes select 2, 'processor', 'intel'
insert into ProductAttributes select 2, 'ram', '16'
insert into ProductAttributes select 2, 'weight', '2'*/

select 
    product, '{' + STRING_AGG( '"' + attribute + '":"' + STRING_ESCAPE(value,'json') + '"' ,',') + '}' as attributes
from ProductAttributes 
group by product

两个产品条目的输出如下
产品属性
1 {"颜色":"红色","大小":"小"}
2 {"处理器":"intel","ram":"16","weight":"2"}

enter image description here

如果您使用的是 SQL Server 2017 之前的版本,则可以使用 string concatenation using SQL XML Path如下
SELECT
    product,
  '{' + STUFF(
    (
    SELECT
      ',' + '"' + attribute + '":"' + STRING_ESCAPE(value,'json') + '"'
    FROM ProductAttributes a
        where a.product = p.product
    FOR XML PATH(''),TYPE
    ).value('.','VARCHAR(MAX)'
    ), 1, 1, ''
  ) + '}' As attributes
from ProductAttributes p
group by product

开发人员将得到相同的结果

enter image description here

我已经更新了上面的 SQL 查询并使用了 String_Escape() 函数 @Eilert 的评论

关于sql-server - 将两列转换为键值 json 对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46168258/

相关文章:

sql - 全外连接

JSON API Wordpress 通过应用上传时不显示特色图片

javascript - 需要将包含img url的Json链接放在<img ng-src中

apache-spark - UDF 中的 Spark classnotfoundException

operators - 为什么 Perl 6 REPL 中没有保留新的运算符定义?

MySQL 加载数据本地 Infile - 路径作为用户变量

c# - 无法摆脱错误 "There is already an open DataReader associated with this Command which must be closed first"

python - 使用 python 在列的基础上为每行创建唯一代码的新列

sql-server - 我的触发器是如何被删除的?

json - 什么是合适的 AWSJSON?