Insert INTO in vb.net - sql

I have 2 databases. In first one I have 10 tables. Second one is only 1 table. I would like to select 1 columns from each table from 1st database and Insert INTO another database. How can I manage this using INSERT INTO statement in VB.net?

I deleted my previous answer saying that you have to manually copy over the data. For now, let's assume you want to do this with a SELECT INTO statement.
The following code shows you how to execute a SQL command on your database using a ADO.NET connection and command object:
' Open a connection to your database (e.g. in a SQL Server): '
Using connection As IDbConnection = New SqlConnection("<Connection string>")
connection.Open()
Try
' Define the SQL command to be executed here: '
Dim command As IDbCommand = connection.CreateCommand()
command.CommandText = "SELECT <...> INTO <...>"
' Execute the command: '
command.ExecuteNonQuery()
Finally
connection.Close()
End Try
End Using

I hope this helps:
From sql side, you'll just need to write a stored procedure to insert into (ten) hash tables and select/insert them into your target table.
In Vb.net, you'll need: a connection object and a command object to call your stored procedure

Related

Export SQL Server data from one database to another

I have a SQL server database of a web application, my requirement is to read 2-3 table data from one source database and insert the data in the destination database. My input will be a Name and an ID, based on that I have to read data from the source database and I have to validate whether the similar Name already exists in the destination database. I have to do this via a C# windows application or a web application.
So far in my research, people have recommended using SqlBulkCopy or an SSIS package, I tried to transfer one table data using the following code.
using (SqlConnection connSource = new SqlConnection(csSource))
using (SqlCommand cmd = connSource.CreateCommand())
using (SqlBulkCopy bcp = new SqlBulkCopy(csDest))
{
bcp.DestinationTableName = "SomeTable";
cmd.CommandText = "myproc";
cmd.CommandType = CommandType.StoredProcedure;
connSource.Open();
using (SqlDataReader reader = cmd.ExecuteReader())
{
bcp.WriteToServer(reader);
}
}
The problem I'm facing is that, I have to copy 2 table data, based on table 1, table 2 value like ID(primary key) changes, I have to update this in the SqlDataReader, so in order to get this new ID in the destination database, I have to insert one table data first, then get the ID, then update this ID in my reader object and then do another SqlBulkCopy, this doesn't look like the ideal way to do this, is there any other to do this?
On the source SQL instance I would create a linked server referencing destination/target SQL instance and then I would create a stored procedure within source database thus:
USE SourceDatabase
GO
CREATE PROCEDURE dbo.ExportSomething
#param1 DataType1,
#param2 DataType2, ...
AS
BEGIN
INSERT LinkedServer.DestinationDatabase.dbo.TargetTable
SELECT ...
FROM dbo.Table1 INNER JOIN dbo.Table2 ....
WHERE Col1 = #param1 AND/OR ...
END
GO
Then, the final step is to call this stored procedure from client application.

ExecuteNonQuery() for Insert query always returning 0

I have the following code in a VB.net application that runs a stored procedure in MS Access. The stored procedure is an insert query based on the results of 2 other queries in the database.
When I run the Insert query manually within Access it runs fine and inserts the records as expected with no error or warnings. However, when I run using the ExecuteNonQuery() from my vb.net application I always get 0 back as the number of records inserted and it doesn't insert any records into the table. The code runs without errors. I have tested the code with other insert queries in the same db and it works fine so I know it's not the code or connection. It appears the problem has something to do with my query, but I can't figure out why it works in Access, but not from ExecuteNonQuery(). Sorry, but I can't post the exact query. I'm using VB.Net 2010 and MS Access 2013.
Please help!!!
Here is a generic version of my stored query:
INSERT INTO Table1 ( TESTID, Field1, Field2, Field3, DateImported )
SELECT DISTINCT Table2.Value1, Table2.Value2, Table2.Value3, Table2.Value4, Date() AS TodaysDate
FROM Table3 INNER JOIN Table2 ON Table3.TESTID = Table2.TESTID
I have tried it with and without the DISTINCT and I still have the same problem
Here is my code:
Dim conn As New OleDbConnection(MyConnectionString)
Try
Using conn
Using cmd As New OleDbCommand("My_Insert_Query", conn)
conn.Open()
cmd.CommandType = CommandType.StoredProcedure
NumRecordsAdded = cmd.ExecuteNonQuery()
End Using
End Using
Catch ex As Exception
MsgBox(ex.Message)
conn.Close()
End Try

INSERT statement status in VBA using ADODB

Say i have a table in Excel:
TableA:
ID,
Name,
Work,
DOB
I have an insert query like:
Insert into TableA(ID,Name,Work,DOB) values (....);
I have created the code to upload this data into SQL Server database using ADODB
The upload works fine but i am trying to have it fill the status of the upload such (Pending, Successful) next to each row. Is there any way to do it?
The ending part of my code is:
For lp = 0 To qryindex - 1 'this loop is used to get query from the array which is stored in previous loop
con.Open 'open the connection
con.Execute qryary(lp), dbfailonerror ' execute the query one by one according to index value
oldValue = Application.ActiveCell.Value
con.Close
Next lp
MsgBox "Data Updated Successfully"
ThisWorkbook.RefreshAll
I need it to update the coulmn(F) as each query in the array is successfully posted

VBA + ADO: Insert without select?

I'm writing some Excel VBA for a user to be able to insert records into a SQL Server table, using ADODB. This is working fine:
Dim conn As New ADODB.connection
conn.Open "<my connection string>"
Dim records As New ADODB.Recordset
records.CursorLocation = adUseClient
records.Open "SELECT TOP 1 * FROM [MyTable]", conn, adOpenStatic, adLockBatchOptimistic, adCmdText
' (Add some stuff here.)
records.UpdateBatch
Something's nagging me, though: is it possible to get the recordset pointed at the right table without doing a SELECT up front? This could get to be a pretty big table, so SELECT * FROM [MyTable] is out. I'm limiting that with a TOP 1, but I'm only doing a write, so it feels like I shouldn't have to do that!
The documentation makes it sound like you can just put a table name in the Source argument:
Use the optional Source argument to specify a data source using one of the following: a Command object variable, an SQL statement, a stored procedure, a table name, [...]
In practice, this doesn't work for me, and all of the following just error out with the message below, like it thinks I'm calling a stored procedure:
records.Open "MyTable", conn, ' [...]
records.Open "[MyTable]", conn, ' [...]
records.Open "[dbo].[MyTable]", conn, ' [...]
The request for procedure 'MyTable' failed because 'MyTable' is a table object.
Is there some syntax I'm missing here, or do I just have to go with the SELECT?

How to check if a table has contents in it

How do I check if a table has contents? Honestly I still don't have any initial codes for it. Do I code it in VB or just use a query?
you definitely need to ask SQL server, so why not just querying 'SELECT COUNT(*) FROM TABLE" ?
which you can put it in a stored procedure.
even you can parametrise the procedure with table name and run exec sql command.
I would not use SELECT COUNT(*) unless you actually care about the actual count - this can be an expensive operation on large tables. If all you care about is whether there are rows or not, much better to use:
IF EXISTS (SELECT TOP (1) NULL FROM dbo.MyTable)
BEGIN
PRINT 'There are rows.';
END
ELSE
BEGIN
PRINT 'There are no rows.';
END
If you don't need to be up-to-the-second, you can use the DMVs for this kind of check. Specifically:
SELECT SUM(row_count)
FROM sys.dm_db_partition_stats
WHERE [object_id] = OBJECT_ID('dbo.MyTable');
The DMV is not always precise due to in-flight transactions and deferred updates, but is generally reliable for ballpark estimates.
Install Microsoft SQL Server Management Studio. You can then view the contents and structure of your tables, easily, through the GUI.
Dim con = New SqlConnection("Data Source=servername;Initial Catalog=myDb;Integrated Security=True")
Dim cmd = New SqlCommand("SELECT Count(*) FROM myTable", con)
con.Open()
Dim count As Integer = CInt(cmd.ExecuteScalar())
con.Close()