Is it possible to insert an entire VB.NET DataTable into a SQL Server at once - sql

I have a SQLClient.DataSet in VB.NET, and I want to insert the entire thing into a SQL Server table without having to do the following:
For Each dr as Datarow in MyDataset
Dim sc As New SqlCommand("INSERT INTO MyNewTable " & _
"VALUES (#column1, #column2)", MyDBConnection)
sc.Parameters.AddWithValue("#column1", dr.Item(0))
sc.Parameters.AddWithValue("#column2", dr.Item(1))
sc.ExecuteNonQuery()
Next
Since I've got close to a million rows (all pretty skinny, so it's not much space), I obviously don't want to run this loop and generate a million INSERT statements.
I know that one option is to use a linked server when I initially fetch the data, since it's coming from another SQL Server, and just have it to the INSERT from there. However, if I already have the data in my application, is there a more efficient way to bulk insert it? Can I somehow pass the DataTable as a parameter to SQL Server and have it sort it out and insert the rows?

try with SqlBulkCopy

With SQL Server 2008 you can use Table-Valued Parameters:
Dim sc As New SqlCommand(
"INSERT INTO MyNewTable (field1, field2,...)"&
"SELECT field1, field2,... FROM #MyTable;", MyDBConnection)
sc.Parameters.AddWithValue("#MyTable", MyDataset)
sc.ExecuteNonQuery()

Use the SqlDataAdapter's InsertCommand to define your Insert query. Then call the DataAdapter's Update Method with your dataset as a parameter to have it push the data.
Something like:
Dim DA As SqlDataAdapter = New SqlDataAdapter
Dim Parm As New SqlParameter
DA.InsertCommand = New SqlCommand("Insert Into tbl1(fld0, fld1, fld2) Values(#fld0, #fld1, #fld2)", conn)
Parm = DA.InsertCommand.Parameters.Add(New SqlParameter ("#fld0", NVarChar, 50, "fld0"))
Parm = sqlDA.InsertCommand.Parameters.Add(New SqlParameter ("#fld1", SqlDbType.NVarChar, 50, "fld1"))
Parm = sqlDA.InsertCommand.Parameters.Add(New SqlParameter ("#fld2", SqlDbType.NVarChar, 50, "fld2"))
DA.Update(dataset1, "tbl1")

You could call .WriteXML() on the DataSet and dump that into the database in one insert.

A way simplier way is to use a table adapter. Then you can use the Fill method to give a datatable as argument :
Dim oStronglyTypedTable As StronglyTypedDataTable = GetTable() 'A custom function that creates your table from wherever you want)
If Not oStronglyTypedTable Is Nothing Then
Using oAdapter As New StronglyTypedTableAdapter
Dim res As Integer = oAdapter.Update(oStronglyTypedTable)
MsgBox(res & " rows have been updated.")
End Using
End If
Do not forget to change your Database "Copy to Output Directory" property to "Do net copy" and set your connection string properly...

Related

Inserting data in mysql using vb.net (n-tier)

there's anyone can help me with my vb.codes? i'm new in vb.net and i want to know how to add data in mysql database using n-tier in vb.net. this is may current code in adding data:
Data Layer:
Public Function addData() As DataTable
Dim myCommand As String = "Insert Into tblItems VALUES (#Itemcode, #Itemname, #Itemdescription, #Itemtype, #Itempricing, #Itemonstock, #Itemprice, #Datemod)"
con.Open()
Dim sda As New MySqlDataAdapter(myCommand, con)
Dim dt As DataTable = New DataTable
sda.Fill(dt)
Return dt
End Function
sorry for my code. i really don't know how can i use that in BLL and PL. please help me. i really want to learn from all of you guys..
PS: sorry for my english i'm a 14 yr old and i want to learn programming. i did a research but i can't find what i'm really looking for. thanks in advance.
To insert a new record in a datatable you need to execute a command and provide the values to be sent to the database table.
You need something like this.
Public Function addData(itmCode as String, itmName as String.... omitted the other values) As Integer
Dim myCommand As String = "Insert Into tblItems VALUES " & _
"(#Itemcode, #Itemname, #Itemdescription, " & _
"#Itemtype, #Itempricing, #Itemonstock, #Itemprice, #Datemod)"
con.Open()
Dim cmd As New MySqlCommand(myCommand, con)
cmd.Parameters.AddWithValue("#ItemCode", itmCode)
cmd.Parameters.AddWithValue("#ItemName", itmName)
.... other parameters for the other values to insert will follow....
Dim rowInserted = cmd.ExecuteNonQuery()
return rowInserted
End Function
This requires that you pass to the function the values through a set of variables which values are added to the parameter collection of the command and finally execute the command.
The execution returns the number of records inserted/changed/deleted.
Notice also that your query doesn't specify a field list, so you need to pass the values to update every single field in the underlying datatable with the exact order.

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.

Get last UserID from SqlServer to textbox control

I have a table customers where each cust has UserID as "A000" now I need to get the last entered ID from the database and display it in my textbox.
Can anyone suggest me how do I do this?
As I have seen many articles describing about
SELECT ##IDENTITY
SELECT SCOPE_IDENTITY()
SELECT IDENT_CURRENT('TableName')
but unable to know where to use it correctly.
And here is how I'm doing it :
Dim strConnection As String = "Data Source=.\SqlExpress;Initial Catalog=Subscription;Integrated Security=True"
'Establish SQL Connection
Dim con As New SqlConnection(strConnection)
'Open database connection to connect to SQL Server
con.Open()
'Data table is used to bind the resultant data
Dim dtusers As New DataTable()
'Create a new data adapter based on the specified query.
Dim da As New SqlDataAdapter("SELECT MAX(UserID) FROM Customers", con)
Dim cmd As New SqlCommandBuilder(da)
da.Fill(dtusers)
con.Close()
Use ExecuteScalar :
Dim comm as new SqlCommand
comm.CommandText = "SELECT MAX(UserID) FROM Customers"
comm.Connection = con
Dim MaxUserID as object = comm.ExecuteScalar()
Use the ExecuteScalar method to retrieve a single value (for example,
an aggregate value) from a database
Side Note : ExecuteScalar() may return a null reference (Nothing in VB.NET) if the result of the command is empty like when there are no records in the table or there is condition that doesn't produce any records. Make sure you check that before assigning the value to your TextBox.

vb.net sqlclient insert output

I have a ms sql table PRODUCTS.
And it has three columns ID (int),NAME (nvarchar),TSTAMP (timestamp)
I want to get new inserted row's both id and timestamp (like multiple select scope_identity).
I can achieve that in sql as following:
INSERT INTO PRODUCTS (NAME)
OUTPUT inserted.ID,inserted.TSTAMP
VALUES ('Example Product')
But how can i read it in vb.net with sqlclient.sqlcommad on insertation? Which function of sqlcommand do i have to use and how? ExecuteReader maybe?
Using the ExecuteReader() method of SqlCommand would work the same as with SELECT.
OUTPUT clause works like a SELECT statement but its usage differs in
INSERT, UPDATE and DELETE commands
Here's a sample code. Try it.
Dim connString As String = "server=Test; database=Test;" + _
"uid=sa; pwd="
Dim conn As New SqlConnection(connString)
Dim cmdString As String = "INSERT INTO PRODUCTS (NAME) " + _
"OUTPUT inserted.ID,inserted.TSTAMP " + _
"VALUES ('Example Product')"
Dim cmd As New SqlCommand(cmdString, conn)
conn.Open()
Dim reader As SqlDataReader = cmd.ExecuteReader()
conn.Close()
Here're some links
Running The OUTPUT Clause From C#
Implementing the OUTPUT Clause in SQL Server 2008

Executing stored procedure in vb.net

I need to execute a stored function in oracle or sql through vb.net.
I created a command object. Depending on the database type(oracle or SQL) i am preparing the
Command text as Select functionName(?,?,?,?,?,?,?,?) from dual; (For Oracle)
Adding the parameter values of the function
Now performing the ExecuteScalar which is not working saying invalid parameter.
This works with ODBC connection string. But ODBC doesn't with 64bit.
My Requirement: Code should execute a user defined stored procedure by taking the values at runtime.
Thanks
Rupesh
Your command text should be just the Stored procedure name without a select, and make sure you set the command type to stored procedure. Check out this link for example:
http://support.microsoft.com/kb/321718
Oracle:
Dim cmd As New OracleCommand
cmd.Connection = conn
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "OracleSP"
Dim p1 As OracleParameter
Dim p2 As OracleParameter
p1 = cmd.Parameters.Add("Param1", OracleType.NVarChar)
p1.Value = "Value1"
p2 = cmd.Parameters.Add("Param2", OracleType.Double)
p2.Value = 10
cmd.ExecuteNonQuery()
SQL Server:
cmd.Connection = conn
cmd.CommandType = CommandType.StoredProcedure
cmd.CommandText = "SqlSP"
cmd.Parameters.Add("#Param1", SqlDbType.Int)
cmd.ExecuteNonQuery()
I am not sure about Oracle as I haven't done it (I think it should work) but with Sql server you can use:
SqlCommandBuilder.DeriveParameters(cmd)
to populate the SqlParametersCollection on the command, instead of setting them like I did.
MSDN documentation
After that you can loop thru them and set your values as necessary.