【发布时间】:2020-08-05 19:27:42
【问题描述】:
我在 SQL Server 上编写了一个存储过程,将以下 JSON 帖子作为输入:
{"sentiment_results": {"polarity": -0.6, "subjectivity": 0.7, "emotions": {"anger": 0.08296050131320953, "disgust": 0.00219865539111197, "fear": 0.07708118110895157, "joy": 0.757244884967804, "surprise": 0.027166856452822685, "sadness": 0.05334791541099548}}, "sentiment_time": "2020-08-04T16:43:47.141948"}
...并且正在使用以下脚本在数据库表中输入数据(post_metric_score 表 -> 每个数据点一行)
INSERT INTO [STAGING].[post_metric_score]([post_id],[metric_id],[score])
SELECT @post_id, 1, try_convert(decimal(12, 8), [score])
FROM OPENJSON(@postJson, '$.sentiment_results')
WITH ([score] FLOAT '$.polarity')
INSERT INTO [STAGING].[post_metric_score]([post_id],[metric_id],[score])
SELECT @post_id, 2, try_convert(decimal(12, 8), [score])
FROM OPENJSON(@postJson, '$.sentiment_results')
WITH ([score] FLOAT '$.subjectivity')
INSERT INTO [STAGING].[post_metric_score]([post_id],[metric_id],[score])
SELECT @post_id, 3, try_convert(decimal(12, 8), [score])
FROM OPENJSON(@postJson, '$.sentiment_results.emotions')
WITH ([score] FLOAT '$.anger')
INSERT INTO [STAGING].[post_metric_score]([post_id],[metric_id],[score])
SELECT @post_id, 4, try_convert(decimal(12, 8), [score])
FROM OPENJSON(@postJson, '$.sentiment_results.emotions')
WITH ([score] FLOAT '$.disgust')
INSERT INTO [STAGING].[post_metric_score]([post_id],[metric_id],[score])
SELECT @post_id, 5, try_convert(decimal(12, 8), [score])
FROM OPENJSON(@postJson, '$.sentiment_results.emotions')
WITH ([score] FLOAT '$.fear')
INSERT INTO [STAGING].[post_metric_score]([post_id],[metric_id],[score])
SELECT @post_id, 6, try_convert(decimal(12, 8), [score])
FROM OPENJSON(@postJson, '$.sentiment_results.emotions')
WITH ([score] FLOAT '$.joy')
该脚本运行良好,但它使用了大量 CPU,因为每个 JSON 帖子运行相同的插入查询 6 次。
有没有办法简化上面的脚本,使其不必多次运行插入语句?
【问题讨论】:
标签: sql json sql-server stored-procedures