我试图使用另一个表的输入将数据插入到表中。尽管这对于许多数据库引擎来说是完全可行的,但我似乎总是很难记住当前SQL引擎(MySQL、Oracle、SQL Server、Informix和DB2)的正确语法。

是否有来自SQL标准(例如SQL-92)的银弹语法允许我插入值而不必担心底层数据库?


当前回答

这是另一个使用带有select的值的示例:

INSERT INTO table1(desc, id, email) 
SELECT "Hello World", 3, email FROM table2 WHERE ...

其他回答

只需在INSERT中使用SELECT子句的括号。例如:

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'
);

已知表列序列时的简单插入:

    Insert into Table1
    values(1,2,...)

简单插入提及列:

    Insert into Table1(col2,col4)
    values(1,2)

当表(#table2)的选定列数等于插入表(Table1)时进行大容量插入

    Insert into Table1 {Column sequence}
    Select * -- column sequence should be same.
       from #table2

当您只想插入表(表1)的所需列时进行大容量插入:

    Insert into Table1 (Column1,Column2 ....Desired Column from Table1)  
    Select Column1,Column2..desired column from #table2
       from #table2
select *
into tmp
from orders

看起来不错,但只有当tmp不存在时才有效(创建并填充)。(SQL服务器)

要插入现有tmp表:

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

要在第一个答案中添加一些内容,当我们只需要另一个表中的几个记录时(在本例中只有一个):

INSERT INTO TABLE1
(COLUMN1, COLUMN2, COLUMN3, COLUMN4) 
VALUES (value1, value2, 
(SELECT COLUMN_TABLE2 
FROM TABLE2
WHERE COLUMN_TABLE2 like "blabla"),
value4);

如果您首先创建表,可以这样使用;

  select * INTO TableYedek From Table

这将插入值,但与创建新的复制表不同。