简体   繁体   中英

Incomplete Data Transfer from VBA to SQL Server

I have a SQL-Server in Azure and want to transfer data from Excel into it using VBA through a VPN Tunnel. It works but out of 801 entries sometimes 320 are transmitted sometimes 324 but always in a range between 300 and 350 never more. They are transfer in the correct order as they are in the excel file. I am not getting an error at all. Just saw in the SQL Table that there are not all entries in there. I tried it some times and colleagues of my as well with the same result. My code is:

Sub Importer(ByVal tableName As String, ByVal importQuery As String, pass As String)

    Dim con As Object
    
    Set con = CreateObject("ADODB.Connection")
    
        con.Open _
                "Driver={ODBC Driver 17 for SQL Server};" & _
                "Server=tcp:myServer,1433;" & _
                "Database=myDB;" & _
                "Uid= admin;" & _
                "Pwd=" & pass & ";" & _
                "TrustServerCertificate=no;" & _
                "Connection Timeout=30;" & _
                "Encrypt=yes;"
        con.Execute importQuery
        con.Close
       
    Set con = Nothing
    
End Sub

While importQuery contails 801 INSERT INTO entries in one query looking like this:

INSERT INTO dbo.table(Variable1, Variable1, Variable1) Values(", 3)
INSERT INTO dbo.table(Variable1, Variable1, Variable1) Values(", 3)
INSERT INTO dbo.table(Variable1, Variable1, Variable1) Values(", 3)

...

I tried to set the timeout up but with no effect. Anyone with an idea what might cause the problem?

Your pseudo-code is syntactically incorrect, but that's irrelevant I guess.

Currently you're doing multiple singleton INSERT statements in an non-transactional manner. Surely your connection is being broken or some other issue happens in the middle of the code executing, resulting in only some of the data being inserted.

Either wrap a transaction around the entire set of INSERT statements. Or even simpler would be to convert them to a single INSERT statement of multiple values, which will be implicitly transactional and potentially more efficient, like so:

INSERT INTO dbo.table(Column1, Column2, Column3)
VALUES
    (ValueA1, ValueA2, ValueA3),
    (ValueB1, ValueB2, ValueB3),
    (ValueC1, ValueC2, ValueC3),
    (ValueD1, ValueD2, ValueD3),
    (ValueE1, ValueE2, ValueE3);

As far as whatever error / issue your application is running into, unfortunately won't be advisable without more details such as a specific error message. But at least the fix I mentioned above will ensure either all or none of the data is consistently inserted.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM