Thursday, August 8, 2013

How to use INSERT query using SELECT statement in SQL Server?

In MSSQL you can insert value from one table to another table using SELECT statement. So using this type of query you can copy one table values to another table without using CREATE TABLE Statement.

Insert all the records from one table to another table:

The below query copy all the values from Mytable to NEW_TABLE. The NEW_TABLE will create automatically.  You don’t need to create the Table structure.

SELECT * INTO NEW_TABLE FROM MyTable


The Below Query will insert the value based on the Where condition of MyTable where Age <32 .="" p="">
SELECT * INTO NEW_TABLE FROM MyTable WHERE Age <32



The Below query will insert the distinct values from Mytable to the new table.

SELECT DISTINCT Name INTO NEW_TABLE FROM MyTable



The Below query will insert only Name column in the Old table of MyTable.

SELECT Name INTO New_Table FROM MyTable



If you already have a same Table structure of MyTable means you can use below insert query to insert the all column values to net table.
INSERT INTO NEW_TABLE SELECT * FROM MyTable


If you already have a same Table structure of MyTable means you can use below insert to insert the particular column.

INSERT INTO new_table (Name,Age) SELECT Name FROM MyTable





No comments: