在PostgreSQL 9.5表中,我有一个psexec -i -s \\Remote-Pc -u USERNAME -p ****** "locationoftheexe\Initializator.exe"
列integer
。
当我尝试在存储过程中更新它时,给定以下JSON数据(一个包含2个对象的数组,每个对象都有一个" social"键)social
变量类型{{ 1}}:
in_users
然后以下代码失败:
jsonb
错误消息:
'[{"sid":"12345284239407942","auth":"ddddc1808197a1161bc22dc307accccc",**"social":3**,"given":"Alexander1","family":"Farber","photo":"https:\/\/graph.facebook.com\/1015428423940942\/picture?type=large","place":"Bochum,
Germany","female":0,"stamp":1450102770},
{"sid":"54321284239407942","auth":"ddddc1808197a1161bc22dc307abbbbb",**"social":4**,"given":"Alxander2","family":"Farber","photo":null,"place":"Bochum,
Germany","female":0,"stamp":1450102800}]'::jsonb
我已尝试将该行更改为:
FOR t IN SELECT * FROM JSONB_ARRAY_ELEMENTS(in_users)
LOOP
UPDATE words_social SET
social = t->'social',
WHERE sid = t->>'sid';
END LOOP;
然后我收到错误:
ERROR: column "social" is of type integer but expression is of type jsonb
LINE 3: social = t->'social',
^
HINT: You will need to rewrite or cast the expression.
为什么PostgreSQL不识别数据是social = t->'social'::int,
?
从JSON-TYPE-MAPPING-TABLE我的印象是JSON号码会自动转换为PostgreSQL数字类型。
答案 0 :(得分:4)
单个基于集合的SQL命令比循环更有效:
UPDATE words_social w
SET social = (iu->>'social')::int
FROM JSONB_ARRAY_ELEMENTS(in_users) iu -- in_user = function variable
WHERE w.sid = iu->>'sid'; -- type of sid?
回答你原来的问题:
为什么PostgreSQL不识别数据是整数?
因为您尝试将jsonb
值转换为integer
。在您的解决方案中,您已经发现需要->>
运算符而不是->
来提取text
,可以将其转换为integer
。
您的第二次尝试又添加了第二个错误:
<击> t->'social'::int
击>
除上述内容外:operator precedence。转换运算符::
比json运算符->
绑定得更强。就像你已经发现的那样,你真的想要:
(t->>'social')::int
dba.SE非常相似:
答案 1 :(得分:0)
我最终使用了:
FOR t IN SELECT * FROM JSONB_ARRAY_ELEMENTS(in_users)
LOOP
UPDATE words_social SET
social = (t->>'social')::int
WHERE sid = t->>'sid';
IF NOT FOUND THEN
INSERT INTO words_social (social)
VALUES ((t->>'social')::int);
END IF;
END LOOP;