【发布时间】:2018-09-25 10:57:02
【问题描述】:
我正在尝试使用参数化的插入语句将数据插入到 SQL Server 表中。
但是我在尝试执行命令时收到错误消息,
-2147217913 从字符串转换日期和/或时间时转换失败
我不明白,因为我已经指定 dtDate 是 addDBDate。传递给它的值是一个日期,即 2018-09-24。我错过了什么?
Dim sSQL As String
Dim ws As Worksheet
Set ws = ThisWorkbook.Sheets(shsName)
OpenDbConnection
Dim sInd As String
Dim dtDatePrice As Date
Dim dScoreWgt As Double
Dim sScoreRat As String
Dim dScoreHlt As Double
Dim dScoreSup As Double
sSQL = "insert into " & sDB & ".dbo.MYTABLE(Ndate, Industry, ScoreOvrWgt, ScoreOvrRat, ScoreHealth, ScoreSupply) " & _
"values('dtDate', 'sInd', 'dScoreWgt', 'sScoreRat', 'dScoreHlt', 'dScoreSup')"
Dim cmd As New ADODB.Command
cmd.ActiveConnection = cn
cmd.CommandType = adCmdText
cmd.CommandText = sSQL
cmd.Parameters.Append cmd.CreateParameter("dtDate", adDBDate, adParamInput)
cmd.Parameters.Append cmd.CreateParameter("sInd", adVarChar, adParamInput, 100)
cmd.Parameters.Append cmd.CreateParameter("dScoreWgt", adDouble, adParamInput)
cmd.Parameters.Append cmd.CreateParameter("sScoreRat", adVarChar, adParamInput, 10)
cmd.Parameters.Append cmd.CreateParameter("dScoreHlt", adDouble, adParamInput)
cmd.Parameters.Append cmd.CreateParameter("dScoreSup", adDouble, adParamInput)
Dim iRow As Integer
iRow = 1
Do Until IsEmpty(ws.Cells(iRow, 3))
dtDatePrice = ws.Cells(iRow, 4)
cmd.Parameters("dtDate").Value = dtDatePrice
cmd.Parameters("sInd").Value = Strings.Trim(ws.Cells(iRow, 6))
If Strings.Trim(ws.Cells(iRow, 8)) = "NA" Then
cmd.Parameters("dScoreWgt").Value = Null
Else
cmd.Parameters("dScoreWgt").Value = ws.Cells(iRow, 8)
End If
cmd.Parameters("sScoreRat").Value = Strings.Trim(ws.Cells(iRow, 9))
If Strings.Trim(ws.Cells(iRow, 14)) = "NA" Then
cmd.Parameters("dScoreHlt").Value = Null
Else
cmd.Parameters("dScoreHlt").Value = ws.Cells(iRow, 14)
End If
If Strings.Trim(ws.Cells(iRow, 15)) = "NA" Then
cmd.Parameters("dScoreSup").Value = Null
Else
cmd.Parameters("dScoreSup").Value = ws.Cells(iRow, 15)
End If
cmd.Execute
irow = irow + 1
loop
【问题讨论】:
-
您的插入语句使用变量名称而不是参数标记指定字符文字。应该是:
"values(?, ?, ?, ?, ?, ?)" -
@DanGuzman 非常感谢。如果您将您的评论作为答案,很乐意将其标记为正确
标签: sql-server excel vba adodb