Is there a way to copy a in memory datatable (vb.net) and its columns(schema) into a sql server new or existing table? And if a column has been added to the temp table is there a way to BulkCopy the data adding the new column into existing sql server table?
Here is what I use to persist a DataTable to SQL Server, it is written in C# but you should be able to convert it rather easily:
public static string CreateCopyTableDataSQLServer(DataTable dt, string tableName, string connectionString)
{
//Create the Destination Table based upon the structure of the DataTable
string sql = string.Empty;
string retValue = string.Empty;
StringBuilder sbu;
try
{
if (dt.Rows.Count == 0)
{
retValue += "The table " + tableName + " was NOT created because the source table contained zero (0) rows of data";
}
else
{
sbu = new StringBuilder(string.Format("IF EXISTS (SELECT * FROM sys.objects WHERE object_id = OBJECT_ID(N'[dbo].[{0}]') AND type in (N'U')) DROP TABLE [dbo].[{0}] ", tableName));
sbu.Append("Create Table " + tableName + " (");
string dataType = string.Empty;
foreach (DataColumn column in dt.Columns)
{
switch (column.DataType.Name)
{
case "String":
dataType = " nvarchar(MAX) ";
break;
case "DateTime":
dataType = " nvarchar(MAX) ";
break;
case "Boolean":
dataType = " nvarchar(MAX) ";
break;
case "Int32":
dataType = " int ";
break;
case "Byte[]":
dataType = " varbinary(8000) ";
break;
default:
dataType = " nvarchar(MAX) ";
break;
}
string columnName = column.ColumnName.ToString();
columnName = columnName.FormatProperNameCase();
columnName = column.ColumnName.ToString().Replace(" ", "_").Replace("-", "_").Replace("#", "_").FormatRemoveNonLettersNumbers();
sbu.Append("[" + columnName + "]" + dataType + " null, ");
}
sbu.Remove(sbu.Length - 2, 2);
sbu.Append(")");
sql = sbu.ToString();
sql = sql.Replace("/", "_").Replace("\\", "_");
//Copy the Data From the Data Table into the destination Table that was created above
bool errorRetValue = SQLServerBulkCopy(dt, sql, tableName, connectionString);
if (!errorRetValue)
{
retValue += " \r\n";
retValue += "There was an error!";
}
}
return retValue;
}
catch (Exception ex)
{
retValue = string.Format("Error - There was a problem with table {0} and thus it's data has NOT been transferred - {1}", tableName, ex.Message);
return retValue;
}
}
public static bool SQLServerBulkCopy(DataTable dt, string Sql, string TableName, string connectionString, bool connectionTypeSQL = true)
{
try
{
if (connectionTypeSQL)
{
using (SqlConnection conn = new SqlConnection(connectionString))
{
conn.Open();
using (SqlBulkCopy sqlcpy = new SqlBulkCopy(conn))
{
using (SqlCommand cmd = new SqlCommand(Sql, conn))
{
cmd.ExecuteNonQuery();
sqlcpy.DestinationTableName = TableName; //copy the datatable to the sql table
sqlcpy.WriteToServer(dt);
}
}
}
return true;
}
else
{
throw new ArgumentOutOfRangeException("This method is only for SQL Server Engines");
}
}
catch (Exception ex)
{
return false;
}
}
For creating a new table:
select *
into YourDb.dbo.NewTable
from #YourTempTable
To append to an existing table:
insert YourDb.dbo.ExistingTable
select *
from #YourTempTable
Where I work they wouldn't allow Linked Servers so I transferred two tables form different servers across using VB.NET:
Copying source Sql table into Datatable
Mapping columns in Datatable
Copying Datatable into destination Sql table
The code is below:
Sub BulkTransferSQLTables(strSchema As String, strTable As String, StrOutputServer As String, StrOutputDatabase As String) ', strEndSrvrDb As String)
Dim DTBulkTransfer As New DataTable
'get table of information
Dim strSchemaTable As String = strSchema & "." & strTable
Dim sqlstring As String = "Select * from " & strSchemaTable
Dim Conn As SqlConnection = New SqlConnection("Data Source=" & PubstrServer & ";Initial Catalog=" & PubstrDatabase & ";Integrated Security=True") 'connection to server end
Dim selectCMD As SqlCommand
Dim adapter As SqlDataAdapter
adapter = New SqlDataAdapter(sqlstring, Conn)
'fill dataset
Conn.Open()
adapter.Fill(DTBulkTransfer)
'Debug.Print(DTBulkTransfer.Rows.Count & " Rows, " & DTBulkTransfer.Columns.Count & " Cols ") 'works
'build create table statement using details of destination table
Dim strColname As String
Dim intRecCount As Integer
'Dim strSchema As String = "SuffolkPseudo"
'Dim strTable As String = "Acute_Supporting"
strSchemaTable = strSchema & "." & strTable
Dim strCreateTableSQL As String = "CREATE TABLE [" & StrOutputDatabase & "].[" & strSchema & "].[" & strTable & "]("
Dim strSQL As String = " select [Statement], [RowNo] = ROW_NUMBER() OVER (ORDER BY Statement) FROM [" & PubstrDatabase & "].[dbo].[vwTableAndColumns] " & _
"where [TABLE_SCHEMA] = '" & strSchema & "' and table_name = '" & strTable & "'"
Dim strSQL2 As String = "" & _
" with CTE as ( " & _
" " & _
strSQL & _
" ) " & _
" " & _
" select count(*) from CTE "
intRecCount = GetSQLTableVal(strSQL2)
For X = 1 To intRecCount
strSQL2 = "" & _
" with CTE as ( " & _
" " & _
strSQL & _
" ) " & _
" " & _
" select * from CTE "
strColname = GetSQLTableVal(strSQL2 & " Where [RowNo] = " & X)
strCreateTableSQL = strCreateTableSQL & " " & Chr(13) & strColname
Next
strCreateTableSQL = Microsoft.VisualBasic.Left(strCreateTableSQL, Microsoft.VisualBasic.Len(strCreateTableSQL) - 1) & ") ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]"
Debug.Print(strCreateTableSQL)
Conn.Close()
Dim Conn2 As SqlConnection = New SqlConnection("Data Source=" & StrOutputServer & ";Initial Catalog=" & StrOutputDatabase & ";Integrated Security=True") 'connection to server end
'create sql string to check if table exists or not.
strSQL = " select count(*) FROM [" & StrOutputDatabase & "].sys.Tables as t1 " & _
" inner join [" & StrOutputDatabase & "].sys.schemas as t2 " & _
" ON t1.schema_id = t2.schema_id" & _
" where t2.name = '" & strSchema & "' " & _
" and t1.name = '" & strTable & "'"
If GetSQLTableValExternalServer(strSQL, StrOutputServer, StrOutputDatabase) > 0 Then
Conn2.Open()
'drop old table in destination area and recreate table.
strSQL = "drop table " & StrOutputDatabase & "." & strSchema & "." & strTable
selectCMD = New SqlCommand(strSQL, Conn2)
selectCMD.CommandTimeout = 600
selectCMD.ExecuteNonQuery()
Conn2.Close()
End If
Conn2.Open()
'create the table structure
selectCMD = New SqlCommand(strCreateTableSQL, Conn2)
selectCMD.CommandTimeout = 600
selectCMD.ExecuteNonQuery()
'list datatable columns
Dim name(DTBulkTransfer.Columns.Count) As String
Dim i As Integer = 0
'transfer to sql database from datatable to newly created empty detsination table
Using bulkcopy As SqlBulkCopy = New SqlBulkCopy(Conn2)
bulkcopy.BulkCopyTimeout = 3000
bulkcopy.DestinationTableName = strSchemaTable
For Each column As DataColumn In DTBulkTransfer.Columns
name(i) = column.ColumnName
Dim ColMap As New SqlBulkCopyColumnMapping(name(i).ToString, name(i).ToString)
bulkcopy.ColumnMappings.Add(ColMap)
Debug.Print("dt COLUMN: " & name(i).ToString)
i += 1
Next
bulkcopy.WriteToServer(DTBulkTransfer)
End Using
Conn2.Close()
MsgBox("Bulk Transfer Complete")
End Sub
Thanks
Eddy Jawed
Related
I have a txt file on my local PC, this has to be check and then line by line uploaded into SQL Server 2016 using a Stored Procedure from MS Access using ADODB. It looks like Access is running always 2 rows fast and then making a short stop.
In MS Access I'm using this function:
Public Function ImportData(FileString As String)
Dim WholeLine As String
Dim cc As Variant
Dim sapPurchaseDocument As String
Dim sapPartNumber As String
Dim sapPartName As String
Dim sapDocumentDate As String
Dim sapSupplier As String
Dim sapPlant As String
Dim sapSLoc As String
Dim sapQuantity As Double
Dim sapUOM As String
Dim sapTargetQuantity As Double
Dim sapDeliveryDate As String
Dim sapPrevQuantity As Double
Dim sapReceivedQuantity As Double
Dim sapIssuedQuantity As Double
Dim sapDeliveredQuantity As Double
Dim sapPurchaseRequisition As String
Dim sapPurchaseRequisitionItem As String
Dim sapCreationIndicatior As String
Dim sapNoOfPositions As Double
Dim totalCount As Integer
Dim sapPurchaseDocumentItem As String
Dim rs As New ADODB.Recordset
Call GetConnection
Set rs.ActiveConnection = myCN
If Right(FileString, 3) = "txt" Then
totalCount = GetRowCount(FileString)
Open FileString For Input As #1
i = 0
Do While Not EOF(1)
Line Input #1, WholeLine
If Left(WholeLine, 3) = "| 4" Then
'Debug.Print WholeLine
cc = Split(WholeLine, "|")
sapPurchaseDocument = Trim(cc(1))
sapPartNumber = Trim(Replace(cc(2), ".", ""))
sapPartName = Trim(Replace(cc(3), "'", ""))
sapDocumentDate = Right(cc(4), 4) & "-" & Mid(cc(4), 4, 2) & "-" & Left(cc(4), 2)
sapSupplier = cc(5)
sapPlant = cc(6)
sapSLoc = cc(7)
sapQuantity = Replace(cc(8), ",", "")
sapUOM = Trim(cc(9))
sapTargetQuantity = Replace(cc(10), ",", "")
sapDeliveryDate = Right(cc(11), 4) & "-" & Mid(cc(11), 4, 2) & "-" & Left(cc(11), 2)
sapPrevQuantity = cc(12)
sapReceivedQuantity = Replace(cc(13), ",", "")
sapIssuedQuantity = Replace(cc(14), ",", "")
sapDeliveredQuantity = Replace(cc(15), ",", "")
sapPurchaseRequisition = Trim(cc(16))
sapPurchaseRequisitionItem = Trim(cc(17))
sapCreationIndicatior = cc(18)
sapNoOfPositions = cc(19)
sapPurchaseDocumentItem = Trim(cc(20))
strSQL = "spInsertUpdateSAPME2M '" & sapPurchaseDocument & "', '" & sapPartNumber & "', '" & sapPartName & "', '" & _
sapDocumentDate & "', '" & sapSupplier & "', '" & sapPlant & "', '" & sapSLoc & "', " & _
sapQuantity & ", '" & sapUOM & "', " & sapTargetQuantity & ", '" & sapDeliveryDate & "', " & _
sapPrevQuantity & ", " & sapReceivedQuantity & ", " & sapIssuedQuantity & ", " & _
sapDeliveredQuantity & ", '" & sapPurchaseRequisition & "', '" & sapPurchaseRequisitionItem & "', '" & _
sapCreationIndicatior & "', '" & sapNoOfPositions & "', '" & sapPurchaseDocumentItem & "'"
rs.Open (strSQL)
DoEvents
End If
i = i + 1
Debug.Print i
Forms!frm_Overview.lblStatus.Caption = "Record " & i & " of " & totalCount & " loaded. Please wait!"
DoEvents
'Refresh
Loop
MsgBox "Import done"
End If
Close #1
End Function
And on SQL Server I have a stored procedure which looks like this:
USE [MOBILEPRINT]
GO
/****** Object: StoredProcedure [dbo].[spInsertUpdateSAPME2M] Script Date: 5/25/2020 11:39:31 AM ******/
SET ANSI_NULLS OFF
GO
SET QUOTED_IDENTIFIER ON
GO
CHANGE NO ACTION
ALTER PROCEDURE [dbo].[spInsertUpdateSAPME2M]
-- Add the parameters for the stored procedure here
#sapPurchaseDocument varchar(50),
#sapPartNumber varchar(50),
#sapPartName varchar(300),
#sapDocumentDate date,
#sapSupplier varchar(50),
#sapPlant varchar(100),
#sapSLoc varchar(50),
#sapQuantity float,
#sapUOM varchar(50),
#sapTargetQuantity float,
#sapDeliveryDate date,
#sapPrevQuantity float,
#sapReceivedQuantity float,
#sapIssuedQuantity float,
#sapDeliveredQuantity float,
#sapPurchaseRequisition varchar(50),
#sapPurchaseRequisitionItem varchar(50),
#sapCreationIndicatior varchar(50),
#sapNoOfPositions varchar(50),
#sapPurchaseDocumentItem varchar(50)
AS
BEGIN TRANSACTION
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
DECLARE #RESULT int
DECLARE #UPDATE_CHECK int
DECLARE #UpdateDate datetime = GetDate()
BEGIN
SELECT #RESULT = COUNT(sapPurchaseDocument) FROM SAP_ME2M WHERE sapPurchaseDocument = #sapPurchaseDocument AND sapPartNumber = #sapPartNumber
IF ISNULL(#RESULT,0) = 0
BEGIN
INSERT INTO SAP_ME2M (
sapPurchaseDocument,
sapPartNumber,
sapPartName,
sapDocumentDate,
sapSupplier,
sapPlant,
sapSLoc,
sapQuantity,
sapUOM,
sapTargetQuantity,
sapDeliveryDate,
sapPrevQuantity,
sapReceivedQuantity,
sapIssuedQuantity,
sapDeliveredQuantity,
sapPurchaseRequisition,
sapPurchaseRequisitionItem,
sapCreationIndicatior,
sapNoOfPositions,
ChangeDate,
sapPurchaseDocumentItem)
VALUES
(#sapPurchaseDocument, #sapPartNumber, #sapPartName, #sapDocumentDate, #sapSupplier, #sapPlant,
#sapSLoc, #sapQuantity, #sapUOM, #sapTargetQuantity, #sapDeliveryDate, #sapPrevQuantity,
#sapReceivedQuantity, #sapIssuedQuantity, #sapDeliveredQuantity, #sapPurchaseRequisition,
#sapPurchaseRequisitionItem, #sapCreationIndicatior, #sapNoOfPositions, #UpdateDate, #sapPurchaseDocumentItem)
END
ELSE
SELECT #UPDATE_CHECK = COUNT(*) FROM SAP_ME2M WHERE
sapPurchaseDocument = #sapPurchaseDocument AND
sapPartNumber = #sapPartNumber AND
sapPartName = #sapPartName AND
sapDocumentDate = #sapDocumentDate AND
sapSupplier = #sapSupplier AND
sapPlant = #sapPlant AND
sapSLoc = #sapSLoc AND
sapQuantity = #sapQuantity AND
sapUOM = #sapUOM AND
sapTargetQuantity = #sapTargetQuantity AND
sapDeliveryDate = #sapDeliveryDate AND
sapPrevQuantity = #sapPrevQuantity AND
sapReceivedQuantity = #sapReceivedQuantity AND
sapIssuedQuantity = #sapIssuedQuantity AND
sapDeliveredQuantity = #sapDeliveredQuantity AND
sapPurchaseRequisition = #sapPurchaseRequisition AND
sapPurchaseRequisitionItem = #sapPurchaseRequisitionItem AND
sapCreationIndicatior = #sapCreationIndicatior AND
sapNoOfPositions = #sapNoOfPositions AND
sapPurchaseDocumentItem = #sapPurchaseDocumentItem
IF #UPDATE_CHECK = 0
BEGIN
UPDATE SAP_ME2M SET
sapPartName = #sapPartName ,
sapDocumentDate = #sapDocumentDate ,
sapSupplier = #sapSupplier ,
sapPlant = #sapPlant ,
sapSLoc = #sapSLoc ,
sapQuantity = #sapQuantity ,
sapUOM = #sapUOM ,
sapTargetQuantity = #sapTargetQuantity ,
sapDeliveryDate = #sapDeliveryDate ,
sapPrevQuantity = #sapPrevQuantity ,
sapReceivedQuantity = #sapReceivedQuantity ,
sapIssuedQuantity = #sapIssuedQuantity ,
sapDeliveredQuantity = #sapDeliveredQuantity ,
ChangeDate = #UpdateDate
WHERE
sapPartNumber = #sapPartNumber AND
sapPartName = #sapPartName AND
sapDocumentDate = #sapDocumentDate AND
sapSupplier = #sapSupplier AND
sapPlant = #sapPlant AND
sapSLoc = #sapSLoc AND
sapPurchaseDocumentItem = #sapPurchaseDocumentItem
END
END
COMMIT TRANSACTION WITH (DELAYED_DURABILITY = ON);
I have to upload around 30000 Records which takes more then an hour at the moment.
If you have suggestions, please let me know.
For fast data transfer, use a disconnected recordset with batch operations enabled.
Dim conn As ADODB.Connection
Call GetConnection
Set conn = myCN
Dim rs As New ADODB.Recordset
rs.CursorLocation = adUseClient
rs.Open "Table1", conn, adOpenForwardOnly, adLockBatchOptimistic
'Disconnect
Set rs.ActiveConnection = Nothing
Dim i As Long
For i = 1 To 3000
rs.AddNew
rs.Fields(1) = i
Next
'Reconnect
Set rs.ActiveConnection = conn
'Batch insert
rs.UpdateBatch
Debug.Print Now()
For me, this executes in 2 seconds, but it highly depends on the location of SQL server.
Then, process further on the data set when uploaded. Processing on a per-record basis is usually going to be slow.
I have some problem when inserting data to database.
I am using mssql.
Private Sub EditMethodAdd_Click()
Dim rs As ADODB.Recordset
Dim introw
Dim strState As String
Dim strsql1 As String
Dim strsql2 As String
Dim all As String
Dim strConn As String
Dim conn As ADODB.Connection
MsgBox ("EditM1.Value:" & EditM1.value)
strConn = "DRIVER=SQL Server;SERVER=CHU-AS-0004;DATABASE=RTC_LaplaceD_DEV;Trusted_Connection=Yes;"
strsql1 = " INSERT INTO dbo.Method(MethodID, MethodClass, Category, Description, Description2, MSA, ReqType, Equipment, Location, Spec1, Spec2, Spec3, Spec4, Spec5, Spec6, PilotingYN) "
strsql2 = " VALUES(EditM1.value, 'Piloting', EditM3.value, Null, Null, Null, Null, EditM2.value, EditM4.value, EditM5.value, EditM6.value, EditM7.value, EditM8.value, EditM9.value, EditM10.value, Null )"
all = strsql1 & strsql2
MsgBox ("ALL" & all)
Set conn = New ADODB.Connection
conn.Open strConn
Set rs = New ADODB.Recordset
rs.Open all, conn
MsgBox ("Insert Success")
EditMethodList.Requery
conn.Close
Set rs = Nothing
Set conn = Nothing
MsgBox "Data has been updated"
EditMethodList.Requery
End Sub
When I check the value for EditM1 by using MsgBox, it shows correct.
But I got error message like this.
Is there anyone who can solve this problem?
Thank you in advance.
Delete the lines:
strsql1 = ...
strsql2 = ...
all = strsql1 & strsql2
and write this instead
all = "INSERT INTO dbo.Method(MethodID, MethodClass, Category, Description, Description2, MSA, ReqType, Equipment, Location, Spec1, Spec2, Spec3, Spec4, Spec5, Spec6, PilotingYN) "
all = all & "VALUES(" & EditM1.value & ", 'Piloting'," & EditM3.value & ", Null, Null, Null, Null," & EditM2.value & "," & EditM4.value & ","
all = all & EditM5.value & "," & EditM6.value & "," & EditM7.value & "," & EditM8.value & "," & EditM9.value & "," & EditM10.value & ", Null )"
If you insert EditM1.value into doublequotes, as you did, VBA read it as a string and it does not refer to its value. You need to concatenate string and values with & to create your query.
You're putting the literal value "EditM1.value" into your SQL: you should instead be sending the Value of the control:
strsql2 = " VALUES(" & EditM1.value & ", 'Piloting', " & _
EditM3.value & ", Null,..." 'etc
If any of the values being sent are not numeric then they should be wrapped in single quotes.
I am opening an SQL Server Connection in EXCEL VBA and on the objMyCmd.Execute line when it is using the SQL script I am getting this error message:
"Run-time error '-2147217900 (80040e14)') Automation error"
I have reviewed other SO posts that seem to reference an issue with the connection string itself, but I don't believe that is the issue as I am able to pull the first few variables listed when eliminating the rest of the SQL script.
I have attempted to review the SQL code to see if I am using an incorrect format, or if the language is not written properly and I am not able to determine the issue. I am hoping with some Q & A we may notice something I have missed in how this is written? Please let me know if there is additional information I can provide, below is the code up to the point of error.
Sub SQL_GetAgentChart()
Dim dtDate As Date
Dim myTable As ListObject
Dim DataServer As String
Dim Database As String
Dim constring As String
DataServer = "GLSSQLMADP2"
Database = "PERF_MGMT_BWRSRV_PROD"
constring = "Driver={SQL Server};Server=" & DataServer & "; Database=" & Database & "; Trusted_Connection=yes"
Dim AVStartDate As Date
Dim AVEndDate As Date
Dim RepID As Long
'Declare variables'
Set objMyConn = New ADODB.Connection
Set objMyCmd = New ADODB.Command
Set objMyRecordset = New ADODB.Recordset
Set myTable = Worksheets("Witness").ListObjects("tblWitness")
AVStartDate = DateValue("Mar 01, 2016")
AVEndDate = DateValue("Mar 31, 2016")
RepID = 2040
'Open Connection'
objMyConn.ConnectionString = constring
objMyConn.Open
'Set and Excecute SQL Command'
Set objMyCmd.ActiveConnection = objMyConn
objMyCmd.CommandText = " " & _
"SELECT PERSN_XTRNL_ID_NR, SOURCE, LOGGINGTS, DD7, CUREREASON, CUREDATE, LNSTATUS " & _
"FROM TTB " & _
"WITH INCALL AS (SELECT T.CUREREASON, CUREVALUE " & _
"FROM TTB T " & _
"JOIN PERSONNEL P ON T.PERSONNELID = P.PERSONNELID " & _
"LEFT JOIN CURETRANSLATE C ON T.CUREREASON = C.CUREREASON AND T.LNSTATUS = C.STATUS " & _
"WHERE T.PERSONNELID = " & RepID & " " & _
"AND LOGGINGTS > '" & AVStartDate & "' " & _
"AND LOGGINGTS < '" & AVEndDate + 1 & "' " & _
"AND INCOMING = 1 " & _
"AND DD7 > 0), OUTCALL AS (SELECT T.CUREREASON, CUREVALUE " & _
"FROM TTB T " & _
"JOIN AVAYA A ON T.UID = A.TTBUID " & _
"LEFT JOIN CURETRANSLATE C ON T.CUREREASON = C.CUREREASON AND T.LNSTATUS = C.STATUS " & _
"WHERE PERSONNELID = " & RepID & " " & _
"AND LOGGINGTS > '" & AVStartDate & "' " & _
"AND LOGGINGTS < '" & AVEndDate + 1 & "' " & _
"AND INCOMING = 0 " & _
"AND A.AVAYAGROUP IN ('15', '1A', '1B', '1C', '1D', '1E', '1F', '1G', '1H') " & _
"AND DD7 > 0) "
objMyCmd.CommandType = adCmdText
objMyCmd.Execute
i'm trying to creat a table on my sql server from a datagridview
here's my code
Form2.ShowDialog()
Dim grid = DirectCast(Me.TabControl1.SelectedTab.Controls(0), DataGridView)
Static Dim header As New ArrayList
Dim sql As String
Dim values As String = ""
connection = New SqlConnection("Data Source=ABDELOUAHED;Initial Catalog=table_creances;integrated security=true")
For Each column As DataGridViewColumn In grid.Columns
column.HeaderText = column.HeaderText.Replace(" ", "_")
column.HeaderText = column.HeaderText.Replace("é", "e")
column.HeaderText = column.HeaderText.Replace("'", "")
header.Add(column.HeaderText)
Next
sql = "CREATE TABLE " & Form2.TextBox1.Text & "(" & header(0) & " int PRIMARY KEY NOT NULL," & header(1) & " int," & header(2) & " int," & header(3) & " real," & header(4) & " real," & header(5) & " date," & header(6) & " date," & header(7) & " real," & header(8) & " int)"
Try
Dim Mycommand As SqlCommand = New SqlCommand(sql, connection)
Mycommand.Connection.Open()
Mycommand.ExecuteNonQuery()
Mycommand.Connection.Close()
Catch ex As Exception
MsgBox(ex.ToString)
End Try
Try
cmdBuilder = New SqlCommandBuilder(adapter)
changes = ds.GetChanges()
If changes IsNot Nothing Then
adapter.Update(changes)
End If
MsgBox("Changes Done")
Catch ex As Exception
MsgBox(ex.ToString)
End Try
the table is created but it contains no value, the update part doesn't work
any help would be very appreciated
What I wanted to do is insert data on the first table, then get the last inserted ID on the first table and insert it on the second. I already got this without transaction, but I can't do it because I need to have transactions later on because I will add a lot of inserts in one go.
This is my code so far..
Take note that this is inside a transaction..
command.CommandText = "INSERT INTO tblCarMaintenance " & _
"(ID_Car, fDate, fMechanic, fOverseer, fDescription, fDateNext, fAmount) " & _
"VALUES (#myCarID, #myDate, #myMechanic, #myOverseer, #myDescription, #myDateNext, #myAmount)"
command.Parameters.Add("#myCarID", SqlDbType.Int).Value = pCarID
command.Parameters.Add("#myDate", SqlDbType.DateTime).Value = myDate
command.Parameters.Add("#myMechanic", SqlDbType.VarChar).Value = pMechanic
command.Parameters.Add("#myOverseer", SqlDbType.VarChar).Value = pOverseer
command.Parameters.Add("#myDescription", SqlDbType.VarChar).Value = pDescription
command.Parameters.Add("#myDateNext", SqlDbType.DateTime).Value = pNext
command.Parameters.Add("#myAmount", SqlDbType.Float).Value = pAmount
command.ExecuteNonQuery()
'insert records on the second table (the problem is here)
command.CommandText = "INSERT INTO tblCarMaintenance2 " & _
"(ID_Main, ID_Supplier, fParts, fAmount) " & _
"VALUES (#myMainID, #mySupplierID, #myParts, #myAmount) " & _
"FROM tblCarMaintenance"
command.Parameters.Add("#myMainID", SqlDbType.Int).Value = myID
command.Parameters.Add("#mySupplierID", SqlDbType.DateTime).Value = myDate
command.Parameters.Add("#myParts", SqlDbType.VarChar).Value = pMechanic
command.Parameters.Add("#myAmount", SqlDbType.VarChar).Value = pOverseer
command.ExecuteNonQuery()
transaction.Commit()
EDIT: #myMainID is the parameter equal to the last inserted ID on tblCarMaintenance
EDIT:
The solution for the problem is this:
command.CommandText = "INSERT INTO tblCarMaintenance " & _
"(ID_Car, fDate, fMechanic, fOverseer, fDescription, fDateNext, fAmount) " & _
"VALUES (#myCarID, #myDate, #myMechanic, #myOverseer, #myDescription, #myDateNext, #myAmount)" & _
"Select SCOPE_IDENTITY()"
command.Parameters.Add("#myCarID", SqlDbType.Int).Value = pCarID
command.Parameters.Add("#myDate", SqlDbType.DateTime).Value = myDate
command.Parameters.Add("#myMechanic", SqlDbType.VarChar).Value = pMechanic
command.Parameters.Add("#myOverseer", SqlDbType.VarChar).Value = pOverseer
command.Parameters.Add("#myDescription", SqlDbType.VarChar).Value = pDescription
command.Parameters.Add("#myDateNext", SqlDbType.DateTime).Value = pNext
command.Parameters.Add("#myAmount", SqlDbType.Float).Value = pAmount
Dim InsertedItemID = command.ExecuteScalar()
command.CommandText = "INSERT INTO tblCarMaintenance2 " & _
"(ID_Main, ID_Supplier, fParts, fAmount) " & _
"VALUES (" & InsertedItemID & ", #mySupplierID, #myParts, #myAmount2) "
command.Parameters.Add("#mySupplierID", SqlDbType.Int).Value = pSupplier
command.Parameters.Add("#myParts", SqlDbType.VarChar).Value = pParts
command.Parameters.Add("#myAmount2", SqlDbType.Float).Value = 12
command.ExecuteNonQuery()
In your first query, edit to:
command.CommandText = "INSERT INTO tblCarMaintenance " & _
"(ID_Car, fDate, fMechanic, fOverseer, fDescription, fDateNext, fAmount) " & _
"VALUES (#myCarID, #myDate, #myMechanic, #myOverseer, #myDescription, #myDateNext, #myAmount)" & _
"Select SCOPE_IDENTITY()";
and change the first command.ExecuteNonQuery() to:
Dim InsertedItemID = command.ExecuteScalar()