Insert all values of a table into another table in SQL - sql

I am trying to insert all values of one table into another. But the insert statement accepts values, but i would like it to accept a select * from the initial_Table. Is this possible?

The insert statement actually has a syntax for doing just that. It's a lot easier if you specify the column names rather than selecting "*" though:
INSERT INTO new_table (Foo, Bar, Fizz, Buzz)
SELECT Foo, Bar, Fizz, Buzz
FROM initial_table
-- optionally WHERE ...
I'd better clarify this because for some reason this post is getting a few down-votes.
The INSERT INTO ... SELECT FROM syntax is for when the table you're inserting into ("new_table" in my example above) already exists. As others have said, the SELECT ... INTO syntax is for when you want to create the new table as part of the command.
You didn't specify whether the new table needs to be created as part of the command, so INSERT INTO ... SELECT FROM should be fine if your destination table already exists.

Try this:
INSERT INTO newTable SELECT * FROM initial_Table

You can insert using a Sub-query as follows:
INSERT INTO new_table (columns....)
SELECT columns....
FROM initial_table where column=value

From here:
SELECT *
INTO new_table_name [IN externaldatabase]
FROM old_tablename

There is an easier way where you don't have to type any code (Ideal for Testing or One-time updates):
Step 1
Right click on table in the explorer and select "Edit top 100 rows";
Step 2
Then you can select the rows that you want (Ctrl + Click or Ctrl + A), and Right click and Copy
(Note: If you want to add a "where" condition, then Right Click on Grid -> Pane -> SQL
Now you can edit Query and add WHERE condition, then Right Click again -> Execute SQL, your required rows will be available to select on bottom)
Step 3
Follow Step 1 for the target table.
Step 4
Now go to the end of the grid and the last row will have an asterix (*) in first column (This row is to add new entry). Click on that to select that entire row and then PASTE (Ctrl + V). The cell might have a Red Asterix (indicating that it is not saved)
Step 5
Click on any other row to trigger the insert statement (the Red Asterix will disappear)
Note - 1: If the columns are not in the correct order as in Target table, you can always follow Step 2, and Select the Columns in the same order as in the Target table
Note - 2 - If you have Identity columns then execute SET IDENTITY_INSERT sometableWithIdentity ON and then follow above steps, and in the end execute SET IDENTITY_INSERT sometableWithIdentity OFF

If you are transferring a lot data permanently, i.e not populating a temp table, I would recommend using SQL Server Import/Export Data for table-to-table mappings.
Import/Export tool is usually better than straight SQL when you have type conversions and possible value truncation in your mapping. Generally, the more complex your mapping, the more productive you are using an ETL tool like Integration Services (SSIS) instead of direct SQL.
Import/Export tool is actually an SSIS wizard, and you can save your work as a dtsx package.

I think this statement might do what you want.
INSERT INTO newTableName (SELECT column1, column2, column3 FROM oldTable);

Dim ofd As New OpenFileDialog
ofd.Filter = "*.mdb|*.MDB"
ofd.FilterIndex = (2)
ofd.FileName = "bd1.mdb"
ofd.Title = "SELECCIONE LA BASE DE DATOS ORIGEN (bd1.mdb)"
ofd.ShowDialog()
Dim conexion1 = "Driver={Microsoft Access Driver (*.mdb)};DBQ=" + ofd.FileName
Dim conn As New OdbcConnection()
conn.ConnectionString = conexion1
conn.Open()
'EN ESTE CODIGO SOLO SE AGREGAN LOS DATOS'
Dim ofd2 As New OpenFileDialog
ofd2.Filter = "*.mdb|*.MDB"
ofd2.FilterIndex = (2)
ofd2.FileName = "bd1.mdb"
ofd2.Title = "SELECCIONE LA BASE DE DATOS DESTINO (bd1.mdb)"
ofd2.ShowDialog()
Dim conexion2 = "Driver={Microsoft Access Driver (*.mdb)};DBQ=" + ofd2.FileName
Dim conn2 As New OdbcConnection()
conn2.ConnectionString = conexion2
Dim cmd2 As New OdbcCommand
Dim CADENA2 As String
CADENA2 = "INSERT INTO EXISTENCIA IN '" + ofd2.FileName + "' SELECT * FROM EXISTENCIA IN '" + ofd.FileName + "'"
cmd2.CommandText = CADENA2
cmd2.Connection = conn2
conn2.Open()
Dim dA2 As New OdbcDataAdapter
dA2.SelectCommand = cmd2
Dim midataset2 As New DataSet
dA2.Fill(midataset2, "EXISTENCIA")

Related

VB.NET tabledapter query insert into from another dataset

I have a situation where I want to Insert into access DB table from MS SQL table.
Same columns and everything.
I have both data sets and both table adapter. I can do what ever I want inside each dataset - any manipulation but I cannot insert from one table to another.
I tried creating an Insert query for destination tableadapter but I cannot get the from working. Tried linking, nothing works.
Searched for days, simply cannot find it.
Thank you for your answer. Can you help me on my example. I'm having trouble setting this up. This is what i got:
Dim myToTableTableAdapter As FirstDataSetTableAdapters.ToTableTableAdapter
myToTableTableAdapter = New FirstDataSetTableAdapters.ToTableTableAdapter()
Dim myFromTableTableAdapter As SecondDataSetTableAdapters.FromTableTableAdapter
myFromTableTableAdapter = New SecondDataSetTableAdapters.FromTableTableAdapter()
myFromTableTableAdapter = myToTableTableAdapter.Clone
'but it doesnt work from here`
What I wanted to do is:
For each drfrom As DataRow In myFromTableTableAdapter.GetData
myToTableTableAdapter.InsertInto(drfrom.item(column01), drfrom.item(column02), drfrom.item(andSoOn))
Next
But it seem to me that this would take so much longer then a "Insert Into From Select" script.
You cannot insert a row from one table into another table, but there are a couple of ways to do what you want. One way (a little verbose) is this:
' sets it up with same schema but empty rows
mOutTable = inTable.Clone
' Now insert the rows:
For Each rowIn In inTable.Rows
r = mOutTable.NewRow()
For Each col In inTable.Columns
r(col.ColumnName) = rowIn(col.ColumnName)
Next
mOutTable.Rows.Add(r)
Next
mOutTable.AcceptChanges
A second way, which is more concise, is this:
outTable = inTable.Clone
For Each inRow As DataRow In inTable.Rows
outTable.LoadDataRow(inRow.ItemArray, False)
End If
outTable.AcceptChanges
Note that both inTable and outTable are ADO.NET DataTable objects. You cannot implement my suggestion on the DataAdapter objects. You must use the DataTable objects. Each DataTable can be associated with a DataAdapter in the standard fashion for ADO.NET:
Dim t as New DataTable()
a.Fill(t);
where a is the ADO.NET DataAdapter. I hope this helps!
Jim

Writing Dynamic SQL Statement

I am very new to Microsoft Access.
I would like to select a column from a table based on the value of a parameter (i.e. my table has columns x, y and z and I have a chosencol parameter which is set by the user using a dropdown.
I can select one / all of the columns using a select command, however, I would like to do this using my parameter chosencol instead.
Having read around, I have found a number of references to using the SET and EXEC commands, however, entering them into the SQL command in Access just yields errors.
Please could someone advise me as to how I go about implementing a dynamic-sql query in Access (in fine detail as I think I am writing the commands in the wrong place at the moment...)
First I created an example table in Access.
Next, I created an example form to query your value. The dropdown is called 'chosencol'. Select a value from the Column Select dropdown and press the "Lookup Value" button.
Here is the code under the "Lookup Value" button's On Click event. A SQL statement is dynamically built with the column you chose. The column is renamed to [FieldName] to that it can by referenced.
Private Sub btnLookup_Click()
Dim rsLookup As New ADODB.Recordset
Dim strSQL As String
strSQL = "select " & chosencol.Value & " as [FieldName] from Table1 where ID=1"
rsLookup.Open strSQL, CurrentProject.Connection, adOpenForwardOnly, adLockReadOnly
If rsLookup.EOF = False Then
txtValue.SetFocus
txtValue.Text = rsLookup![FieldName]
End If
rsLookup.Close
End Sub
When the button is pushed, the value from whatever column you selected will be returned. For this simple example, I'm always returning row 1's data.
I'm pretty sure you can't do that in straight SQL. However, you can create the SQL string in VBA code and save it as a query.
CurrentDB.CreateQueryDef("MyQueryName", "SELECT " & chosencol & " FROM MyTable")
Now, MyQueryName will be a permanent query in your database and can be referenced wherever you want.
If chosencol is a multi-select dropdown, you'll have to read the selected values into an array and then write the array to one concatenated string and use that instead.

Problems with field names and appending files in Access SQL

Okay, so I have nearly 200 tables in an Access database. The tables are of plant species abundance data, and I would like to combine them into a master data file. Each table contains basically the same columns of species; however, many are spelled slightly differently.
When I run an SQL query in MS Access it won't let me append the tables with each other because of the field names being spelled just a little different.
Any thoughts that would help?
The query I am running is an append query:
INSERT INTO masterTable SELECT * FROM siteTable
and, as an example, the differences in field names are pretty minor
(e.g. "Spp.A" vs "SppA" or "SpeciesOne" vs "Species1")
Thanks for any help,
Paul
You'll need to use vba for this, you'll also need to change the column names I'm using in the masterTable, which in my example are just column1, column2 & column3, and to set the maximum column index in a couple of places (I've stuck some comments in, so you can see what needs to be changed).
If you dont usually use vba, Create a form with a button, and a click event for the button & put this code in it, then open the form and click the button.
Dim db As Database
Dim tdf As TableDef
Dim ii As Long
dim sql as String
Set db = CurrentDb()
docmd.setwarnings false
For Each tdf In db.TableDefs
'change column list as required:
sql = "INSERT INTO masterTable (Column1, Column2, Column3) SELECT "
'change 2 to maximum column number - 1:
for ii = 0 to 2
sql = sql & tdf.Fields(ii).Name
'change 2 to maximum column number - 1 again:
if ii < 2 then
sql = sql & ","
end if
next
sql = sql & ")"
docmd.runsql sql
Next
docmd.setwarnings true
This should work I think. (I'm hoping there's no syntax errors, as I havent tested it, but the logic isnt exactly rocket science)
Hope this helps

Insert VB.net Data Table into a Visual Foxpro table

My company wants to slowly switch over some old programs that are written in Visual FoxPro 6.0. The problem is that we have a bunch of programs that still reference FoxPro tables.
I have a query that pulls information down to a data table in vb.net. What do I need to do to insert the information from the data table into a FoxPro table.
This is the initial query that get's put into a data table.
Dim SConn As New OleDbConnection(conn)
Dim da As OleDbDataAdapter
Dim dt As New DataTable
Dim sSql As String = "SELECT DISTINCT * FROM DWEmployee where cono <> 'XX' AND officeno <> 'XX' AND cono <> '' AND officeno <> ''"
SConn.Open()
da = New OleDbDataAdapter(sSql, SConn)
da.SelectCommand.CommandTimeout = 90
da.Fill(dt)
SConn.Close()
What do I need to do to replicate this Foxpro code in VB.net
select distinct * from (the data table) into table gp_emps
This will be my connection string for my FoxPro Table if I need it.
Dim FConnString As String = "Provider=vfpoledb;Data Source=Z:\update_dwprm01\gp_emps.DBF;Collating Sequence=general;"
Dim FPdbConnection As New OleDbConnection(FConnString)
Thanks in advance.
You appear to be on the right track. A few minor issues. The connection string should have the provider as
Provider=vfpoledb.1;
The Data Source component of the string should point to the physical directory where the .dbf files are located and NOT the specific .DBF file itself.
Data Source=Z:\YourShareOnServer\SomePath
The query itself looks ok as you have it coded. HOWEVER, when you DO get more into .net select, insert, update, delete, you will DEFINITELY need to look into using PARAMETERIZED queries to prevent SQL-Injection (even though not practical with VFP since it would just choke on comment / hack attempts), but is still good to be in the practice.
Build your Command and have "?" as a place-holder for the "parameters", then add parameters in the same order as your "?" placements in the query such as:
dim OleDbCommand oCmd = new OleDbCommand();
oCmd.CommandText = "SELECT DISTINCT * from DWEmployee " _
+ "where cono <> ? and officeno <> ? AND cono <> '' AND officeno <> ''"
' Only sampling with first 2 as parameters to get the idea...
oCmd.Parameters.Add( "parmCONO", "XX" );
oCmd.Parameters.Add( "parmOffice", "XX" );
SConn.Open()
da = New OleDbDataAdapter(oCmd, SConn)
da.SelectCommand.CommandTimeout = 90
continue with filling the data table...
I've had many posts out for VFP, OleDB and C#, but the principles all are the same. It's been a while since using OleDB connectivity but you are getting there.

How do I query SQL data then insert or update depending on the result

I am a beginner at this. But let me explain what I need to do and show you my code
I have a CSV file.
inside the CSV I have a projectnumber, city,state,country
I have a SQL table with the same column
I want to use vb.net to check if projectnumber exists in sql table
if exists then I want to run update statement.
if it does not exists then I want to run insert statement.
I have the program working . but I am just wondering if this would be the correct way or my code is some hack way of doing it.
LEGEND:
DTTable is data table with CSV inside
DT is data table with SQL result data
First I fill insert all lines in the CSV into a data table
Dim parser As New FileIO.TextFieldParser(sRemoteAccessFolder & "text.csv")
parser.Delimiters = New String() {","}
parser.ReadLine()
Do Until parser.EndOfData = True
DTTable.Rows.Add(parser.ReadFields())
Loop
parser.Close()
then I use oledbdataadapter to run the select query and fill another data table with the result of the select statement
SQLString = "select * from tblProjects where ProjectID='" & DTTable.Rows.Item(i).Item("ProjectNumber") & "'"
da = New OleDb.OleDbDataAdapter(SQLString, Conn)
da.Fill(dt)
then I run if statement
If dt.Rows.Count = 0 then
SQLString = "INSERT STATEMENT HERE"
oCmd = New OleDb.OleDbCommand(SQLString, Conn)
oCmd.ExecuteNonQuery()
Else
SQLString = "UPDATE STATEMENT HERE"
oCmd = New OleDb.OleDbCommand(SQLString, Conn)
oCmd.ExecuteNonQuery()
End if
ALL above code is run inside a for loop, to go through all the lines in the CSV
For i = 0 To DTTable.Rows.Count - 1
what do you think?
please advise
thank you
Personally, I wouldn't use .NET. I would import the table into a temp SQL Server table and then write my queries to insert/update data from the temp table to the regular table. This is certainly the way you want to go if the dataset is large.
If this is a process you need to repeat frequently, you could make an SSIS package.
I'd run the select query using datareader = command.ExecuteReader(). Then:
If datareader.Read() then
'Update query using datareader(0) as a where predicate goes here
ElseIf datareader(0) = Nothing then
'Insert query goes here
End If
I should say, I'm a relative novice too though, so maybe others can suggest a more elegant way of doing it.