SQL - Inserindo linhas em uma tabela usando uma instrução SELECT


Volta a página anterior

Volta ao Menu Principal


Desenvolvido por DORNELLES Carlos Alberto - Analista de Sistemas - Brasília DF. - cad_cobol@hotmail.com

SQL - Inserindo linhas em uma tabela usando uma instrução SELECT - Inserting rows into a table using a Select-Statement
  • Você pode usar uma instrução SELECT dentro de uma instrução INSERT para inserir zero, uma ou mais linhas selecionadas da tabela ou view que você especificar em outro tabela.
    You can use a select-statement within an INSERT statement to insert zero, one, or more rows selected from the table or view you specify into another table.
  • A tabela que você vai selecionar as linhas pode ser a mesma tabela que você está inserindo.
    The table you select the rows from can be the same table you are inserting into.
  • Se as colunas são da mesma tabela, o SQL criará uma tabela temporária de resultados que contém as linhas selecionadas e, em seguida, vai fazer o INSERT a partir da tabela temporária na tabela de destino.
    If they are the same table, SQL will create a temporary result table containing the selected rows and then insert from the temporary table into the target table.
  • Um uso para esse tipo de instrução INSERT é mover dados em uma tabela que você criou para dados resumidos.
    One use for this kind of INSERT statement is to move data into a table you created for summary data.
  • Por exemplo, suponha que você queira uma tabela que mostra os compromissos de tempo de cada funcionário para projetos.
    For example, suppose you want a table that shows each employee's time commitments to projects.
  • Você poderia criar uma tabela chamada EMPTIME com as colunas EMPNUMBER, PROJNUMBER, STARTDATE, ENDDATE e TTIME e, em seguida, usar a seguinte instrução INSERT para preencher a tabela:
    You could create a table called EMPTIME with the columns EMPNUMBER, PROJNUMBER, STARTDATE, ENDDATE, and TTIME, and then use the following INSERT statement to fill the table:
        INSERT INTO CORPDATA.EMPTIME
              (EMPNUMBER, PROJNUMBER, STARTDATE, ENDDATE)
               SELECT EMPNO
               ,      PROJNO
               ,      EMSTDATE
               ,      EMENDATE
                 FROM CORPDATA.EMP_ACT
  • A instrução SELECT incorporada na instrução INSERT não é diferente da instrução de seleção que você usa para recuperar dados.
    The select-statement embedded in the INSERT statement is no different from the select-statement you use to retrieve data.
  • Com a exceção de FOR READ ONLY, FOR UPDATE OF, ou a cláusula OPTIMIZE, você pode usar todas as palavras-chave, funções de coluna, e as técnicas utilizadas para recuperar os dados.
    With the exception of FOR READ ONLY, FOR UPDATE OF, or the OPTIMIZE clause, you can use all the keywords, column functions, and techniques used to retrieve data.
  • O SQL insere todas as linhas que atendem às condições de pesquisa na tabela especificada.
    Inserir linhas de uma tabela em outra tabela não afeta nenhuma linha existente na tabela de origem ou na tabela de destino.
    SQL inserts all the rows that meet the search conditions into the table you specify.
    Inserting rows from one table into another table does not affect any existing rows in either the source table or the target table.
  • Você deve considerar o seguinte ao inserir várias linhas em uma tabela:
    O número de colunas listado implícita ou explicitamente na instrução INSERT deve ser igual ao número de colunas listadas na instrução de seleção.
    You should consider the following when inserting multiple rows into a table:
    The number of columns implicitly or explicitly listed in the INSERT statement must equal the number of columns listed in the select-statement.
  • Os dados nas colunas que você está selecionando devem ser compatíveis com as colunas nas quais você está inserindo ao usar o comando INSERT com instruções de seleção.
    The data in the columns you are selecting must be compatible with the columns you are inserting into when using the INSERT with select-statement.
  • Caso a instrução de seleção incorporada no INSERT não retorne nenhuma linha, um SQLCODE de 100 será retornado para alertá-lo de que nenhuma linha foi inserida.
    Se você inserir linhas com êxito, o campo SQLERRD (3) do SQLCA terá um número inteiro representando o número de linhas SQL realmente inseridas.
    In the event the select-statement embedded in the INSERT returns no rows, an SQLCODE of 100 is returned to alert you that no rows were inserted.
    If you successfully insert rows, the SQLERRD(3) field of the SQLCA has an integer representing the number of rows SQL actually inserted.
  • Se o SQL encontrar um erro ao executar a instrução INSERT, o SQL interromperá a operação.
    Se você especificar COMMIT (* CHG), COMMIT (* CS), COMMIT (* ALL) ou COMMIT (* RR), nada será inserido na tabela e um SQLCODE negativo será retornado.
    Se você especificar COMMIT (* NONE), todas as linhas inseridas antes do erro permanecerão na tabela.
    If SQL finds an error while running the INSERT statement, SQL stops the operation.
    If you specify COMMIT (*CHG), COMMIT(*CS), COMMIT (*ALL), or COMMIT(*RR), nothing is inserted into the table and a negative SQLCODE is returned.
    If you specify COMMIT(*NONE), any rows inserted prior to the error remain in the table.
  • Você pode unir duas ou mais tabelas com uma instrução select em uma instrução INSERT.
    Carregada dessa maneira, a tabela pode ser operada com instruções UPDATE, DELETE e INSERT, porque as linhas existem como linhas fisicamente armazenadas em uma tabela.
    You can join two or more tables with a select-statement in an INSERT statement.
    Loaded in this manner, the table can be operated on with UPDATE, DELETE, and INSERT statements, because the rows exist as physically stored rows in a table.