我遇到了从 EXCEL VBA 代码传递到 SQL Server 存储过程的日期参数的问题。
存储过程采用两个日期参数 @FromDate
和 @ToDate
。我想在 Excel 中使用从单元格中获取的日期值执行此过程。
问题是,从单元格到过程的日期以格式 "dd/mm/yyyy"
传递,而不管我在 excel 单元格中所做的任何格式更改。而 SQL 过程接受格式 "yyyy-mm-dd"
或 "yyyy-mon-dd"
或 "yyyy/mm/dd"
或 "dd-mon-yyyy"
。
程序抛出错误:
"Conversion failed when converting date and/or time from character string" for the dates passed from excel (in the format "dd/mm/yyyy"
我使用的vba代码是(引用https://www.mssqltips.com/sqlservert...to-sql-server/)
Private Sub CommandButton1_Click()
Dim FromDate As Date
Dim ToDate As Date
FromDate = Format(Sheets("Sheet1").Range("B1").Value, "yyyy-mm-dd") 'Pass value from cell B1 to SellStartDate variable
ToDate = Format(Sheets("Sheet1").Range("B2").Value, "yyyy-mm-dd") 'Pass value from cell B2 to SellEndDate variable
MsgBox FromDate
MsgBox ToDate
'Pass the Parameters values to the stored procedure used in the data connection
With ActiveWorkbook.Connections("TestConnection").OLEDBConnection
.CommandText = "EXEC dbo.spr_TestProcedure '" & FromDate & "','" & ToDate & "'"
ActiveWorkbook.Connections("TestConnection").Refresh
End With
End Sub.
有没有办法以 SQL Server 过程接受的格式传递日期?如果没有其他选择,那么我将不得不选择将我的过程参数类型设置为 varchars 并将它们转换为日期。
感谢您对此的帮助!
最佳答案
您可以将日期作为 char() 传递给 sp,并将其转换为日期。
关于excel - VBA 将日期参数传递给 SQL Server 存储过程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39961565/