SQL Server SELECT into existing table SQL Server SELECT into existing table sql-server sql-server

SQL Server SELECT into existing table


SELECT ... INTO ... only works if the table specified in the INTO clause does not exist - otherwise, you have to use:

INSERT INTO dbo.TABLETWOSELECT col1, col2  FROM dbo.TABLEONE WHERE col3 LIKE @search_key

This assumes there's only two columns in dbo.TABLETWO - you need to specify the columns otherwise:

INSERT INTO dbo.TABLETWO  (col1, col2)SELECT col1, col2  FROM dbo.TABLEONE WHERE col3 LIKE @search_key


There are two different ways to implement inserting data from one table to another table.

For Existing Table - INSERT INTO SELECT

This method is used when the table is already created in the database earlier and the data is to be inserted into this table from another table. If columns listed in insert clause and select clause are same, they are not required to list them. It is good practice to always list them for readability and scalability purpose.

----Create testableCREATE TABLE TestTable (FirstName VARCHAR(100), LastName VARCHAR(100))----INSERT INTO TestTable using SELECTINSERT INTO TestTable (FirstName, LastName)SELECT FirstName, LastNameFROM Person.ContactWHERE EmailPromotion = 2----Verify that Data in TestTableSELECT FirstName, LastNameFROM TestTable----Clean Up DatabaseDROP TABLE TestTable

For Non-Existing Table - SELECT INTO

This method is used when the table is not created earlier and needs to be created when data from one table is to be inserted into the newly created table from another table. The new table is created with the same data types as selected columns.

----Create a new table and insert into table using SELECT INSERTSELECT FirstName, LastNameINTO TestTableFROM Person.ContactWHERE EmailPromotion = 2----Verify that Data in TestTableSELECT FirstName, LastNameFROM TestTable----Clean Up DatabaseDROP TABLE TestTable

Ref 1 2


It would work as given below :

insert into Gengl_Del Select Tdate,DocNo,Book,GlCode,OpGlcode,Amt,Narration from Gengl where BOOK='" & lblBook.Caption & "' AND DocNO=" & txtVno.Text & ""