Insert into … values ( SELECT … FROM … )

前端 未结 26 2421
我在风中等你
我在风中等你 2020-11-21 05:40

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 t

相关标签:
26条回答
  • 2020-11-21 06:20
    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
    
    0 讨论(0)
  • 2020-11-21 06:21

    This can be done without specifying the columns in the INSERT INTO part if you are supplying values for all columns in the SELECT part.

    Let's say table1 has two columns. This query should work:

    INSERT INTO table1
    SELECT  col1, col2
    FROM    table2
    

    This WOULD NOT work (value for col2 is not specified):

    INSERT INTO table1
    SELECT  col1
    FROM    table2
    

    I'm using MS SQL Server. I don't know how other RDMS work.

    0 讨论(0)
提交回复
热议问题