我在excel中遇到一个奇怪的问题ADODB.Connection/Recordset
。我必须承认,我不熟悉VBA / VB6和ADO。
我正在使用excel-addin中的函数从SQL-Server中的列返回价格。因此我称之为标量值函数。此函数有三个参数,只有第一个是必需的。如果我提供第二个(datetime
)参数,我会收到一个时间错误。
这是完整的功能,虽然我认为它不相关:
Const connStr As String = "Connection-String"
Private conn As ADODB.Connection
Public Function GetClaimPriceByPartNumber(partNumber As String, Optional claimSubmittedDateEnd As String = "", Optional currencyName As String = "EUR") As String
If conn Is Nothing Then
Set conn = New ADODB.Connection
conn.ConnectionString = connStr
End If
If conn.State <> 1 Then conn.Open
If Trim(currencyName) = "" Then
currencyName = "EUR"
End If
If Trim(claimSubmittedDateEnd) = "" Then
claimSubmittedDateEnd = "NULL"
Else
claimSubmittedDateEnd = "CONVERT(DATETIME, '" & SQLDate(claimSubmittedDateEnd) & "', 102)"
End If
Dim str As String
str = "SELECT COALESCE([dbo].[_GetClaimPriceByPartNumber]('" & partNumber & "'," & claimSubmittedDateEnd & ",'" & currencyName & "'),-1)As Price"
' even a static datetime does not work: CONVERT(DATETIME, '2013-11-11', 102) '
On Error GoTo Exception
Dim rs As ADODB.Recordset
Set rs = New ADODB.Recordset
rs.Open str, conn, adOpenStatic, adLockReadOnly
On Error GoTo Exception
If rs.EOF Then
GetClaimPriceByPartNumber = "part not claimed or no price found"
Else
Dim price As Double
price = rs!price
If price < 0 Then
GetClaimPriceByPartNumber = "N/A"
Else
GetClaimPriceByPartNumber = Round(price, 2)
End If
End If
Escape:
If Not rs Is Nothing Then
If rs.State = adStateOpen Then rs.Close
End If
Exit Function
Exception:
GetClaimPriceByPartNumber = Err.Description
End Function
我无法在sql-server中重现此超时。我已经使用了探查器来查看使用了什么sql。但即使这样也会立即在SSMS中返回结果:
declare @p1 int
set @p1=NULL
declare @p3 int
set @p3=557064
declare @p4 int
set @p4=98305
declare @p5 int
set @p5=NULL
exec sp_cursoropen @p1 output,N'SELECT COALESCE([dbo].[_GetClaimPriceByPartNumber](''1271-4303'',CONVERT(DATETIME, ''2013-11-11'', 102),''EUR''),-1)As Price',@p3 output,@p4 output,@p5 output
select @p1, @p3, @p4, @p5
如果您认为这很重要,我可以发帖_GetClaimPriceByPartNumber
。
我在我的智慧结束。也许你知道发生了什么或者我可以尝试/改进什么。
答案 0 :(得分:1)
而不是使用CONVERT
函数
claimSubmittedDateEnd = "CONVERT(DATETIME, '" & SQLDate(claimSubmittedDateEnd) & "', 102)"
尝试将值作为文本传递给函数并让它处理转换。可以使用Application.Text
或Format
将日期格式化为VBA中的字符串。