How to insert data from one table to another table in SQL
1. INSERT DATA FROM ONE TABLE TO ANOTHER TABLE IN THE SAME DATABASE
INSERT INTO <TABLE1> (FIELD1,FILED2,..FIELDN)
VALUES (SELECT FILED1,FILED2,.. FIELDN FROM <TABLE2> WHERE CONDITION)
Ex:
1. INSERT INTO employees (EMPCODE,EMPNAME,NOTES) VALUES (SELECT EMPCODE,EMPNAME,'ANYNOTES' AS NOTES FROM oldemployeestable)
2. INSERT INTO employees (EMPCODE,EMPNAME,NOTES) VALUES (SELECT EMPCODE,EMPNAME,'ANYNOTES' AS NOTES FROM oldemployeestable WHERE empcity like '%hyd%')
|
2. INSERT DATA FROM ONE TABLE TO ANOTHER TABLE (ALL COLUMNS)
This Query insert the all columns to the table2 from table1
INSERT INTO table2 SELECT * FROM table1
Ex.
1. INSERT INTO employees SELECT * FROM oldemployees
2. INSERT INTO employees SELECT * FROM oldemployees WHERE basic_salary>10000
|
3. INSERT DATA FROM ONE DATABASE TO OTHER (ALL COLUMNS)
INSERT INTO databasename.dbo.table2 SELECT * FROM databasename.dbo.table1
Ex.
1. INSERT INTO paydb1.dbo.employees SELECT * FROM paydb2.dbo.oldemployees
2. INSERT INTO paydb1.dbo.employees (SELECT * FROM paydb2.dbo.oldemployees WHERE
basic_salary>10000)
|
IMPLEMENT IN VB.NET
This is function to execute the sql query
Public Function ExecuteSQLQuery(ByVal SQLQueryString As String) As Boolean
Dim err As Boolean = True
Dim SqlConn As New SqlClient.SqlConnection
Dim Sqlcmmd As New SqlClient.SqlCommand
Try
SqlConn.ConnectionString = ConnectionStrinG
SqlConn.Open()
Sqlcmmd.Connection = SqlConn
Sqlcmmd.CommandText = SQLQueryString
Sqlcmmd.CommandType = CommandType.Text
Sqlcmmd.ExecuteNonQuery()
Catch ex As Exception
MsgBox(ex.Message)
err = False
Finally
SqlConn.Close()
SqlConn.Dispose()
Sqlcmmd.Connection = Nothing
End Try
Return err
End Function
Calling the function
ExecuteSQLQuery (INSERT INTO employees SELECT * FROM oldemployees)
No comments:
Post a Comment