You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将SQL表1数据批量插入为含JSON字段的SQL表2?

批量插入Table1数据到Table2(含JSON字段)

假设Table1和Table2的结构已创建完成:

  • Table1:id, name, gender, age, country, ambition
  • Table2:id, name, details json(JSON类型字段)

下面针对主流数据库提供批量插入的SQL语句:

1. MySQL/MariaDB

利用JSON_OBJECT()函数构造JSON对象,通过INSERT ... SELECT完成批量插入:

INSERT INTO Table2 (id, name, `details json`)
SELECT 
    id,
    name,
    JSON_OBJECT(
        'gender', gender,
        'age', age,
        'country', country,
        'ambition', ambition
    ) AS `details json`
FROM Table1;

2. PostgreSQL

使用json_build_object()生成JSON对象:

INSERT INTO Table2 (id, name, "details json")
SELECT 
    id,
    name,
    json_build_object(
        'gender', gender,
        'age', age,
        'country', country,
        'ambition', ambition
    ) AS "details json"
FROM Table1;

若需更高效的JSONB存储格式,可替换为jsonb_build_object()。

3. SQL Server

方法一:手动拼接JSON(适合字段较少场景)

需注意处理字段中的双引号,避免格式错误:

INSERT INTO Table2 (id, name, [details json])
SELECT 
    id,
    name,
    JSON_QUERY(
        '{' +
        '"gender":"' + REPLACE(gender, '"', '\"') + '",' +
        '"age":"' + CAST(age AS VARCHAR) + '",' +
        '"country":"' + REPLACE(country, '"', '\"') + '",' +
        '"ambition":"' + REPLACE(ambition, '"', '\"') + '"' +
        '}'
    ) AS [details json]
FROM Table1;

方法二:FOR JSON PATH(自动处理特殊字符,更安全)

INSERT INTO Table2 (id, name, [details json])
SELECT 
    id,
    name,
    (SELECT gender, age, country, ambition FOR JSON PATH, WITHOUT_ARRAY_WRAPPER) AS [details json]
FROM Table1;

WITHOUT_ARRAY_WRAPPER确保返回单个JSON对象而非数组,符合需求。

4. Oracle(12c及以上)

使用JSON_OBJECT()函数构造JSON:

INSERT INTO Table2 (id, name, "details json")
SELECT 
    id,
    name,
    JSON_OBJECT(
        'gender' VALUE gender,
        'age' VALUE age,
        'country' VALUE country,
        'ambition' VALUE ambition
    ) AS "details json"
FROM Table1;

内容的提问来源于stack exchange,提问作者Shan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.03 17:51:28