Select * into from Srctbl Insert into Select 5 from Srctbl
As above Desttbl and SRCTBL are two table names respectively.
The above two sentences are inserted srctbl data into the DESTTBL, but the two sentences are different:
- The first sentence (select to from) requires that the target table (DESTTBL) does not exist because it is created automatically when it is inserted.
- The second sentence (insert to select from) requires that the target table (DESTTBL) be present, so we can insert a constant in addition to the field of the source table (SRCTBL), as in the example: 5, because the target table already exists.
The following two snippets of code from the Netizen's blog, because he also extracted my article, so each other excerpts, for users to view.
SELECT INTO
--1. Create a test tableCreate TABLETable1 (Avarchar(Ten), Bvarchar(Ten), Cvarchar(Ten), CONSTRAINT [Pk_table1] PRIMARY KEY CLUSTERED(AASC ) ) on [PRIMARY] GO --2. Create test DataInsert intoTable1Values('Zhao','ASDs',' -') Insert intoTable1Values('Money','ASDs',' -') Insert intoTable1Values('Sun','ASDs',' the') Insert intoTable1Values('Li','ASDs',NULL) GO --3.SELECT to from statement CREATE table Table2 and copy dataSelectA,c intoTable2 fromTable1GO --4. Display the updated resultsSelect * fromTable2GO --5. Deleting a test tableDrop TABLETable1Drop TABLETable2
INSERT INTO Select
--1. Create a test tableCreate TABLETable1 (Avarchar(Ten), Bvarchar(Ten), Cvarchar(Ten), CONSTRAINT [Pk_table1] PRIMARY KEY CLUSTERED(AASC ) ) on [PRIMARY] Create TABLETable2 (Avarchar(Ten), Cvarchar(Ten), Dint, CONSTRAINT [Pk_table2] PRIMARY KEY CLUSTERED(AASC ) ) on [PRIMARY] GO --2. Create test DataInsert intoTable1Values('Zhao','ASDs',' -') Insert intoTable1Values('Money','ASDs',' -') Insert intoTable1Values('Sun','ASDs',' the') Insert intoTable1Values('Li','ASDs',NULL) GO Select * fromTable2--3.INSERT into SELECT statement to replicate table dataInsert intoTable2 (A, C, D)SelectA,c,5 fromTable1GO --4. Display the updated resultsSelect * fromTable2GO --5. Deleting a test tableDrop TABLETable1Drop TABLETable2
Select INTO and insert into Select two table copy statements