我正在尝试使用文本文件作为输入从SQL Server提取数据,但出现错误:
将varchar转换为数值数据类型的算术溢出错误
请让我知道以下代码是否错误或需要添加其他内容:
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
答案 0 :(得分:3)
您的输入文件中似乎有无效数据。最好的办法是清理数据或在执行查询之前检查值。另外,您的代码容易受到SQL注入的攻击。如果此文件中包含9; delete from FRA_RETAIL; --
的一行怎么办?
对于这类查询,您应使用parameters(假设COM_A_NO为十进制(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
此外,强烈建议在代码中添加一些错误处理。