我有一个用户表,我希望将字符串列foo转换为带有{" oldfield":< foo在当前行中的值>},但我似乎无法找到正确的语法。我直接使用psql命令行界面。
这就是我的尝试:
ALTER TABLE user_schema.user ALTER COLUMN "foo" SET DATA TYPE json USING '{"oldfield": "foo"}';
这会将字段更改为{" oldfield":" foo"},而不是foo列的实际值。我还尝试了以下组合,所有这些组合都因语法错误而失败。有任何想法吗?感谢
ALTER TABLE user_schema.user ALTER COLUMN "foo" SET DATA TYPE json USING '{"oldfield": foo}';
ERROR: invalid input syntax for type json
DETAIL: Token "foo" is invalid.
CONTEXT: JSON data, line 1: {"oldfield": foo...
ALTER TABLE user_schema.user ALTER COLUMN "foo" SET DATA TYPE json USING '{"oldfield": \"foo\"}';
ERROR: invalid input syntax for type json
DETAIL: Token "\" is invalid.
CONTEXT: JSON data, line 1: {"oldfield": \...
ALTER TABLE user_schema.user ALTER COLUMN "foo" SET DATA TYPE json USING '{"oldfield": 'foo'}';
ERROR: syntax error at or near "foo"
LINE 1: ...Metadata" SET DATA TYPE json USING '{"oldfield": 'foo...
^
ALTER TABLE user_schema.user ALTER COLUMN "foo" SET DATA TYPE json USING '{"oldfield": `foo`}';
ERROR: invalid input syntax for type json
DETAIL: Token "`" is invalid.
CONTEXT: JSON data, line 1: {"oldfield": `...
ALTER TABLE user_schema.user ALTER COLUMN "foo" SET DATA TYPE json USING '{"oldfield": user.foo}';
ERROR: invalid input syntax for type json
DETAIL: Token "user" is invalid.
CONTEXT: JSON data, line 1: {"oldfield": user...
ALTER TABLE user_schema.user ALTER COLUMN "foo" SET DATA TYPE json USING '{"oldfield": user_schema.user.foo}';
ERROR: invalid input syntax for type json
DETAIL: Token "user_schema" is invalid.
CONTEXT: JSON data, line 1: {"oldfield": user_schema...
ALTER TABLE user_schema.user ALTER COLUMN "foo" SET DATA TYPE json USING '{"oldfield": foo}';
ERROR: invalid input syntax for type json
DETAIL: Token "foo" is invalid.
答案 0 :(得分:3)
create table my_table(foo text);
insert into my_table values
('first'),
('second');
alter table my_table
alter column foo set data type json
using json_build_object('oldfield', foo);
select *
from my_table;
foo
-------------------------
{"oldfield" : "first"}
{"oldfield" : "second"}
(2 rows)