Insert into … values ( SELECT … FROM … )

2018-12-31 01:27发布

I am trying to INSERT INTO a table using the input from another table. Although this is entirely feasible for many database engines, I always seem to struggle to remember the correct syntax for the SQL engine of the day (MySQL, Oracle, SQL Server, Informix, and DB2).

Is there a silver-bullet syntax coming from an SQL standard (for example, SQL-92) that would allow me to insert the values without worrying about the underlying database?

22条回答
妖精总统
2楼-- · 2018-12-31 01:53
select *
into tmp
from orders

Looks nice, but works only if tmp doesn't exists (creates it and fills). (SQL sever)

To insert into existing tmp table:

set identity_insert tmp on

insert tmp 
([OrderID]
      ,[CustomerID]
      ,[EmployeeID]
      ,[OrderDate]
      ,[RequiredDate]
      ,[ShippedDate]
      ,[ShipVia]
      ,[Freight]
      ,[ShipName]
      ,[ShipAddress]
      ,[ShipCity]
      ,[ShipRegion]
      ,[ShipPostalCode]
      ,[ShipCountry] )
      select * from orders

set identity_insert tmp off
查看更多
春风洒进眼中
3楼-- · 2018-12-31 01:54

Just use parenthesis for SELECT clause into INSERT. For example like this :

INSERT INTO Table1 (col1, col2, your_desired_value_from_select_clause, col3)
VALUES (
   'col1_value', 
   'col2_value',
   (SELECT col_Table2 FROM Table2 WHERE IdTable2 = 'your_satisfied_value_for_col_Table2_selected'),
   'col3_value'
);
查看更多
美炸的是我
4楼-- · 2018-12-31 01:55

Most of the databases follow the basic syntax,

INSERT INTO TABLE_NAME
SELECT COL1, COL2 ...
FROM TABLE_YOU_NEED_TO_TAKE_FROM
;

Every database I have used follow this syntax namely, DB2, SQL Server, MY SQL, PostgresQL

查看更多
君临天下
5楼-- · 2018-12-31 01:56

Here is another example where source is taken using more than one table:

INSERT INTO cesc_pf_stmt_ext_wrk( 
  PF_EMP_CODE    ,
  PF_DEPT_CODE   ,
  PF_SEC_CODE    ,
  PF_PROL_NO     ,
  PF_FM_SEQ      ,
  PF_SEQ_NO      ,
  PF_SEP_TAG     ,
  PF_SOURCE) 
SELECT
  PFl_EMP_CODE    ,
  PFl_DEPT_CODE   ,
  PFl_SEC         ,
  PFl_PROL_NO     ,
  PF_FM_SEQ       ,
  PF_SEQ_NO       ,
  PFl_SEP_TAG     ,
  PF_SOURCE
 FROM cesc_pf_stmt_ext,
      cesc_pfl_emp_master
 WHERE pfl_sep_tag LIKE '0'
   AND pfl_emp_code=pf_emp_code(+);

COMMIT;
查看更多
裙下三千臣
6楼-- · 2018-12-31 01:57

Instead of VALUES part of INSERT query, just use SELECT query as below.

INSERT INTO table1 ( column1 , 2, 3... )
SELECT col1, 2, 3... FROM table2
查看更多
还给你的自由
7楼-- · 2018-12-31 01:58

You could try this if you want to insert all column using SELECT * INTO table.

SELECT  *
INTO    Table2
FROM    Table1;
查看更多
登录 后发表回答