Does anyone know or have an example of getting data from 1 table to another?
it is using an SQL SERVER EXPRESS, and 2 tables are practically the same, 1 was used as a temporary table by a fronend client.. so my backend client needs to move items from the temp tables to my other tables.
Do I need to use a forward only cursor and a for loop?
I presume i open a connection, use a command object to query the database that would come back to a DataSet
?
I iterate over the for loop and call insert records using the COMMAND
object of ADO.NET
Is there not a better way of doing it ?
If the columns of the two tables are the same:
INSERT INTO TABLE_1
SELECT * FROM TABLE_2
If not all the columns are the same, you can do it like this:
INSERT INTO TABLE_1 (common_column1, common_column2, common_column3)
SELECT common_column1, common_column2, common_column3 FROM TABLE_2
After that you can update the columns that are not equal. Or you can insert a hardcoded value on the columns that aren't equal:
INSERT INTO TABLE_1 (common_column1, common_column2, common_column3, diff_column_1, diff_column_2)
SELECT common_column1, common_column2, common_column3, '1', '2' FROM TABLE_2
You can do this in SQL only, something like:
SELECT *
INTO theNewTable
FROM FirstTable dept
WHERE 1 = 1;
Put into a strored procedure or execute it directly as a command.
Note that: the INTO
will creates a new table with the same structure as the first one and copy all the rows from the first table into it. If you want to create only the table not to populate the rows and copy them into the new created table us a always-falsy expression. for example "1 = 0".
You can use DataTable.Copy
http://msdn.microsoft.com/fr-fr/library/system.data.datatable.copy.aspx
You can also use DataTable.ImportRow
Link : http://msdn.microsoft.com/fr-fr/library/system.data.datatable.importrow.aspx
TSQL : You can also use : INSERT SELECT
query in stored procedure.
You can insert data using this
INSERT INTO TABLE (columnname1, columnname2, columnname3,.....)
SELECT columnname1, columnname2, columnname3 FROM TBL
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.