Codechef4u is a community for computer professionals,by computer professionals,just like you; who loves sharing and helping each others,Join them
Share your post

Insert into select statement

Insert into select statement:

With SQL you can copy data from one table and insert into another table using SQL Insert into select statement.

Syntax:

If using different table with same columns

INSERT INTO FirstTable
SELECT * FROM SecondTable;

Different table with some same columns only

INSERT INTO FirstTable
(column_name(s))
SELECT column_name(s)
FROM SecondTable;

You can use same table also

INSERT INTO FirstTable
SELECT * FROM FirstTable;
OR
INSERT INTO FirstTable
(column_name(s))
SELECT column_name(s)
FROM FirstTable;


Example:

How to Insert duplicate records from same table ?

Below example explain how I can insert duplicate records from same table,my requirment is I want to duplicate product with different countryid same discount price for country india.

INSERT INTO ProductDiscounts ([ProductId],
             [CountryId] ,
            [DiscountPrice],
            [TaxRate])
             
            SELECT [ProductId],
             2,
            [DiscountPrice],
            [TaxRate] FROM ProductDiscounts WHERE ProductId=(SELECT TOP 1 id FROM products WHERE
            productcode='MX-IND-001') AND
            countryId=(SELECT TOP 1 id from Country WHERE CountryCode='IN')

 

Example with different tables:

How to Insert records from one table to another table?

INSERT INTO Products ([ProductCode],
            [Type] ,
            [Description],
            [isActive])
             
            SELECT [ProductCode],
            [ProductType],
            [Description],
            [IsAvailable] FROM SellableProducts WHERE
            countryCode='IN'
 
 
 

Invalid entry,please enter valid data.

Loading