AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / dba / Perguntas / 199005
Accepted
VansFannel
VansFannel
Asked: 2018-03-01 01:14:24 +0800 CST2018-03-01 01:14:24 +0800 CST 2018-03-01 01:14:24 +0800 CST

Seleção aninhada: insira valores na tabela com duas subconsultas

  • 772

Estou desenvolvendo um procedimento armazenado para SQL Server 2016.

Eu tenho que fazer isso (a seguinte instrução sql não funciona):

Insert into AggregationChildren (AggregationId, AggregationChildrenId, Position)
SELECT Parent, Serial, Position
FROM
    OPENJSON (@json, '$.Aggregations')
    WITH (  Parent nvarchar(20) '$.Parent',
            Children nvarchar(max) AS JSON )
        CROSS APPLY 
            OPENJSON (Children)
            WITH ( Serial nvarchar(20), Position int)

Meu problema é que AggregationIde AggregationChildrenIdsão inteiros e Parente Serialsão nvarchar(20).

Existe uma relação entre Parente AggregationId, e entre Seriale AggregationChildrenId. Eu posso obtê-lo usando a Codetabela.

Eu sei como posso fazer isso quando tenho que inserir valores para uma coluna:

Insert into AggregationChildren (AggregationId)
    Select CodeId from Code Where Serial = (SELECT Parent
    FROM
        OPENJSON (@json, '$.Aggregations')
        WITH (  Parent nvarchar(20) '$.Parent',
                Children nvarchar(max) AS JSON )
            CROSS APPLY 
                OPENJSON (Children)
                WITH ( Serial nvarchar(20), Position int))

Os dados que estou tentando inserir são:

{
    ...,
    "Aggregations": [{
        "Parent": "88962730000000004051",
        "Children": [{
            "Serial": "81861400000000020227",
            "Position": "1"
        }, {
            "Serial": "81861400000000033191",
            "Position": "2"
        }, {
            "Serial": "81861400000000046051",
            "Position": "3"
        },
        ...
        ]
    }, {
        "Parent": "88962730000000016653",
        "Children": [{
            "Serial": "81861400000001825849",
            "Position": "1"
        }, {
            "Serial": "81861400000001832643",
            "Position": "2"
        }, {
            "Serial": "81861400000001841911",
            "Position": "3"
        }, {
            "Serial": "81861400000001850803",
            "Position": "4"
        }, {
            "Serial": "81861400000001862474",
            "Position": "5"
        }, {
            "Serial": "81861400000001874774",
            "Position": "6"
        }, {
            "Serial": "81861400000001884159",
            "Position": "7"
        }, {
            "Serial": "81861400000001898352",
            "Position": "8"
        }, {
            "Serial": "81861400000001904764",
            "Position": "9"
        },
        ...
        ]
    }]
}

Mas, como posso fazer isso se tiver que usar dois Select CodeId from Code Where Serial = (SELECT ...?

Acho que tenho que fazer algo assim mas sem fazer o mesmo select três vezes:

 Insert into AggregationChildren (AggregationId, AggregationChildrenId, Position)
    Select CodeId from Code Where Serial = (SELECT Parent
    FROM
        OPENJSON (@json, '$.Aggregations')
        WITH (  Parent nvarchar(20) '$.Parent',
                Children nvarchar(max) AS JSON )
            CROSS APPLY
                OPENJSON (Children)
                WITH ( Serial nvarchar(20), Position int)), 
    Select CodeId from Code Where Serial = (SELECT Serial
    FROM
        OPENJSON (@json, '$.Aggregations')
        WITH (  Parent nvarchar(20) '$.Parent',
                Children nvarchar(max) AS JSON )
            CROSS APPLY
                OPENJSON (Children)
                WITH ( Serial nvarchar(20), Position int)), 
    SELECT Position
    FROM
        OPENJSON (@json, '$.Aggregations')
        WITH (  Parent nvarchar(20) '$.Parent',
                Children nvarchar(max) AS JSON )
            CROSS APPLY
                OPENJSON (Children)
                WITH ( Serial nvarchar(20), Position int)
sql-server t-sql
  • 1 1 respostas
  • 2651 Views

1 respostas

  • Voted
  1. Best Answer
    McNets
    2018-03-01T04:52:28+08:002018-03-01T04:52:28+08:00

    Se entendi corretamente:

    create table AggregationChildren(AggregationId int, AggregationChildrenId int, Position int);
    create table Code (CodeID int, Serial nvarchar(20));
    insert into Code values
    (1, '88962730000000004051'),
    (2, '81861400000000020227'),
    (3, '81861400000000033191'),
    (4, '81861400000000046051'),
    (5, '88962730000000016653'),
    (6, '81861400000001825849'),
    (7, '81861400000001832643'),
    (8, '81861400000001841911'),
    (9, '81861400000001850803'),
    (10, '81861400000001862474'),
    (11, '81861400000001874774'),
    (12, '81861400000001884159'),
    (13, '81861400000001898352'),
    (14, '81861400000001904764');
    GO
    
    14 linhas afetadas
    
    declare @json nvarchar(max);
    set @json = '
    {
        "Aggregations": [{
            "Parent": "88962730000000004051",
            "Children": [{
                "Serial": "81861400000000020227",
                "Position": "1"
            }, {
                "Serial": "81861400000000033191",
                "Position": "2"
            }, {
                "Serial": "81861400000000046051",
                "Position": "3"
            }
            ]
        }, {
            "Parent": "88962730000000016653",
            "Children": [{
                "Serial": "81861400000001825849",
                "Position": "1"
            }, {
                "Serial": "81861400000001832643",
                "Position": "2"
            }, {
                "Serial": "81861400000001841911",
                "Position": "3"
            }, {
                "Serial": "81861400000001850803",
                "Position": "4"
            }, {
                "Serial": "81861400000001862474",
                "Position": "5"
            }, {
                "Serial": "81861400000001874774",
                "Position": "6"
            }, {
                "Serial": "81861400000001884159",
                "Position": "7"
            }, {
                "Serial": "81861400000001898352",
                "Position": "8"
            }, {
                "Serial": "81861400000001904764",
                "Position": "9"
            }
            ]
        }]
    }
    ';
    

    > -- extrai campos json
    > ;com x como
    > (
    > SELECIONAR
    > Pai,
    > Série,
    > Posição
    > DE
    > OPENJSON (@json, '$.Agregações')
    > WITH (Parent nvarchar(20) '$.Parent', Filhos nvarchar(max) AS JSON)
    > APLICAÇÃO CRUZADA
    > OPENJSON (Crianças)
    > COM (Serial nvarchar(20), Posição int)
    >)
    > INSERT INTO AggregationChildren (AggregationId, AggregationChildrenId, Position)
    > SELECIONE c1.CodeID, c2.CodeID, Posição
    > DE x
    > JOIN Código c1
    > ON c1.Serial = x.Parent
    > JOIN Código c2
    > ON c2.Serial = x.Serial;
    > IR
    >
    12 linhas afetadas
    >

    SELECT * FROM AggregationChildren;
    GO
    
    AgregationId | AgregaçãoChildrenId | Posição ------------: | --------------------: | -------: 1 | 2 | 1 1 | 3 | 2 1 | 4 | 3 5 | 6 | 1 5 | 7 | 2 5 | 8 | 3 5 | 9 | 4 5 | 10 | 5 5 | 11 | 6 5 | 12 | 7 5 | 13 | 8 5 | 14 | 9

    dbfiddle aqui

    • 2

relate perguntas

  • SQL Server - Como as páginas de dados são armazenadas ao usar um índice clusterizado

  • Preciso de índices separados para cada tipo de consulta ou um índice de várias colunas funcionará?

  • Quando devo usar uma restrição exclusiva em vez de um índice exclusivo?

  • Quais são as principais causas de deadlocks e podem ser evitadas?

  • Como determinar se um Índice é necessário ou necessário

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host

    • 12 respostas
  • Marko Smith

    Como fazer a saída do sqlplus aparecer em uma linha?

    • 3 respostas
  • Marko Smith

    Selecione qual tem data máxima ou data mais recente

    • 3 respostas
  • Marko Smith

    Como faço para listar todos os esquemas no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Listar todas as colunas de uma tabela especificada

    • 5 respostas
  • Marko Smith

    Como usar o sqlplus para se conectar a um banco de dados Oracle localizado em outro host sem modificar meu próprio tnsnames.ora

    • 4 respostas
  • Marko Smith

    Como você mysqldump tabela (s) específica (s)?

    • 4 respostas
  • Marko Smith

    Listar os privilégios do banco de dados usando o psql

    • 10 respostas
  • Marko Smith

    Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL?

    • 4 respostas
  • Marko Smith

    Como faço para listar todos os bancos de dados e tabelas usando o psql?

    • 7 respostas
  • Martin Hope
    Jin conectar ao servidor PostgreSQL: FATAL: nenhuma entrada pg_hba.conf para o host 2014-12-02 02:54:58 +0800 CST
  • Martin Hope
    Stéphane Como faço para listar todos os esquemas no PostgreSQL? 2013-04-16 11:19:16 +0800 CST
  • Martin Hope
    Mike Walsh Por que o log de transações continua crescendo ou fica sem espaço? 2012-12-05 18:11:22 +0800 CST
  • Martin Hope
    Stephane Rolland Listar todas as colunas de uma tabela especificada 2012-08-14 04:44:44 +0800 CST
  • Martin Hope
    haxney O MySQL pode realizar consultas razoavelmente em bilhões de linhas? 2012-07-03 11:36:13 +0800 CST
  • Martin Hope
    qazwsx Como posso monitorar o andamento de uma importação de um arquivo .sql grande? 2012-05-03 08:54:41 +0800 CST
  • Martin Hope
    markdorison Como você mysqldump tabela (s) específica (s)? 2011-12-17 12:39:37 +0800 CST
  • Martin Hope
    Jonas Como posso cronometrar consultas SQL usando psql? 2011-06-04 02:22:54 +0800 CST
  • Martin Hope
    Jonas Como inserir valores em uma tabela de uma consulta de seleção no PostgreSQL? 2011-05-28 00:33:05 +0800 CST
  • Martin Hope
    Jonas Como faço para listar todos os bancos de dados e tabelas usando o psql? 2011-02-18 00:45:49 +0800 CST

Hot tag

sql-server mysql postgresql sql-server-2014 sql-server-2016 oracle sql-server-2008 database-design query-performance sql-server-2017

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve