I have successfully loaded the datatable object with data from the table in the Excel file. How do I use this data table object in an UPDATE query to update an existing SQL Server table?
I encounter this error:
Exception has been thrown by the target of an invocation.
at System.RuntimeMethodHandle.InvokeMethod(Object target, Object[] arguments, Signature sig, Boolean constructor) at System.Reflection.RuntimeMethodInfo.UnsafeInvokeInternal(Object obj, Object[] parameters, Object[] arguments) at System.Reflection.RuntimeMethodInfo.Invoke(Object obj, BindingFlags invokeAttr, Binder binder, Object[] parameters, CultureInfo culture) at System.RuntimeType.InvokeMember(String name, BindingFlags bindingFlags, Binder binder, Object target, Object[] providedArgs, ParameterModifier[] modifiers, CultureInfo culture, String[] namedParams) at Microsoft.SqlServer.Dts.Tasks.ScriptTask.VSTATaskScriptingEngine.ExecuteScript()
Public Sub Main()
Dim fileToTest As String
Dim SheetName As String
Dim connectionString As String
Dim excelConnection As OleDbConnection
Dim excelCommand As OleDbCommand
Dim ODA As OleDbDataAdapter
Dim dtExcel As New DataTable()
Dim SQLConn As SqlClient.SqlConnection
Dim SQLCmd As SqlClient.SqlCommand
Dim SQLPara As SqlClient.SqlParameter
'open a connection to the excel file
fileToTest = "C:\Users\testuser\Documents\test\mytestfile.xls"
connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" & "Data Source=" &
fileToTest & ";Extended Properties=""Excel 8.0;HDR=YES;IMEX=1"""
excelConnection = New OleDbConnection(connectionString)
excelConnection.Open()
'open a SQL connection to the LRPSF_Source_DB SQL Server DB
connectionString = "Data Source=mysqlserver.net\sqlentdb1d;Trusted_Connection=True;DATABASE=LRPSF_Source_DB;CONNECTION RESET=FALSE"
SQLConn = New SqlClient.SqlConnection(connectionString)
SQLConn.Open()
'fetch the data from TEST table in Excel file using a command query and store in datatable object
SheetName = "TEST$"
excelCommand = excelConnection.CreateCommand()
excelCommand.CommandText = "SELECT * FROM [" & SheetName & "]"
excelCommand.CommandType = CommandType.Text
ODA = New OleDbDataAdapter(excelCommand)
ODA.Fill(dtExcel) '<- this datatable object is filled with the data successfully
'using the dtExcel datatable as a table input, update the existing dbo.TEST_INPUT_SIMPLE SQL Server table
SQLCmd = SQLConn.CreateCommand()
SQLCmd.CommandText = "UPDATE TIS SET TIS.MY_COLUMN = TISX.MY_COLUMN " &
"FROM dbo.TEST_INPUT_SIMPLE TIS INNER JOIN @source AS TISX " &
"ON TIS.UPDATE_ID = TISX.UPDATE_ID"
SQLCmd.CommandType = CommandType.Text
SQLCmd.Parameters.AddWithValue("@source", dtExcel).SqlDbType = SqlDbType.Structured
SQLCmd.ExecuteNonQuery() '<-- the program errors on this line
Dts.TaskResult = ScriptResults.Success
End Sub