简体   繁体   中英

Arithmetic overflow error converting varchar to data type numeric -VBA

I am trying to fetch data from SQL Server using a text file as input, but I'm getting an error:

Arithmetic overflow error converting varchar to data type numeric

Please let me know if the below code is wrong or anything else needs to be added:

Dim cnn As New ADODB.Connection
Dim rst As New ADODB.Recordset
Dim ConnectionString As String
Dim StrQuery As String
Dim iCols As Integer
Dim X As Double
Dim TXT As String
Dim Y As String
Dim A As Double

strcon = "Provider=SQLOLEDB;Data Source=SERVER1;Initial Catalog=MYDB;Integrated Security=SSPI;"
cnn.Open strcon
cnn.CommandTimeout = 900

Open "C:\Users\Gaurav.Shrivastava\Desktop\SLIp\New folder\TESTING.txt" For Input As 1
X = 0

Do While Not EOF(1)
    Line Input #1, TXT
    Y = Val(TXT)
    A = Y
    StrQuery = "Select * from FRA_RETAIL where COM_A_NO=" & A & ""
    rst.Open StrQuery, cnn
    X = X + 1
Loop

For iCols = 0 To rst.Fields.Count - 1
    Worksheets("Sheet1").Cells(1, iCols + 1).Value = rst.Fields(iCols).Name
Next

Sheets(1).Range("A2").CopyFromRecordset rst
'rst.Close
'cnn.Close
'Set rst = Nothing
'ActiveWorkbook.Close SaveChanges:=True
'Application.Quit

'Application.ActiveWindow.Close

It looks like there is invalid data in your input file. The best move is to cleanup your data or to check the value prior execution the query. Also, your code is vulnerable to SQL Injections. What if there is a line in this file, containing 9; delete from FRA_RETAIL; -- 9; delete from FRA_RETAIL; -- 9; delete from FRA_RETAIL; -- ?

You should use parameters for such type of queries (assuming COM_A_NO is decimal(18,0)):

Sub ProcessLine(ByRef A As String)

    Dim Cn As ADODB.Connection
    Dim Cm As ADODB.Command
    Dim Pm As ADODB.Parameter
    Dim Rs as ADODB.Recordset

    Set Cn = New ADODB.Connection
    Cn.Open "Provider=SQLOLEDB;Data Source=SERVER1;Initial Catalog=MYDB;Integrated Security=SSPI;"
    Set Cm = New ADODB.Command
    With Cm
        .ActiveConnection = Cn
        .CommandText = "Select * from FRA_RETAIL where COM_A_NO=TRY_CAST(? as DECIMAL(18,0));"
        .CommandType = adCmdText

        Set Pm = .CreateParameter("no", adVarChar, adParamInput, 200, A)

        .Parameters.Append Pm

        Set Rs = .Execute
    End With

End Sub

Also, it is highly recommended to add some error handling in your code.

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