[英]SQL Server : error converting data type nvarchar to decimal
The following piece of code is opening a JSON message and is inserting the value that corresponds to the '$.disgust' field on the JSON message on the post_metric_score
table.以下代码将打开 JSON 消息,并在
post_metric_score
表的 JSON 消息中插入与“$.disgust”字段对应的值。 It works fine in general except when the value is something like that:它通常工作正常,除非值是这样的:
"disgust": 5.6780936574796215e-05.
The error that I get is我得到的错误是
Error converting data type nvarchar to decimal
将数据类型 nvarchar 转换为十进制时出错
INSERT INTO [Database].[post_metric_score] ([post_id], [metric_id], [score])
SELECT @post_id, 4, [score]
FROM OPENJSON(@postJson, '$.sentiment_results.emotions')
WITH ([score] DECIMAL(12, 8) '$.disgust')
I tried to add a convert statement in the SELECT statement but it doesn't work eg我试图在 SELECT 语句中添加一个转换语句,但它不起作用,例如
SELECT @post_id, 6, CONVERT(DECIMAL(12,8), [score]) AS [score]
Any ideas of what I am doing wrong?关于我做错了什么的任何想法?
Try retrieving the value as a string and using try_convert()
:尝试将值作为字符串检索并使用
try_convert()
:
INSERT INTO [Database].[post_metric_score]([post_id], [metric_id], [score])
SELECT @post_id, 4, try_convert(decimal(12, 8), try_convert(float, [score]))
FROM OPENJSON(@postJson, '$.sentiment_results.emotions')
WITH ([score] VARCHAR(255) '$.disgust') ;
Or use a float directly:或者直接使用浮点数:
INSERT INTO [Database].[post_metric_score]([post_id], [metric_id], [score])
SELECT @post_id, 4, try_convert(decimal(12, 8), try_convert(float, [score]))
FROM OPENJSON(@postJson, '$.sentiment_results.emotions')
WITH ([score] float '$.disgust') ;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.