excel - VBA 将日期参数传递给 SQL Server 存储过程

标签 excel sql-server-2008 parameter-passing

我遇到了从 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/

相关文章:

Excel 数字格式字符串(例如 "@"、 "$-409]d-mmm-yy;@") - 完整的引用可用性?

arrays - 范围对象可以容纳的单元格数量是否有限制?

sql - 查询一个二进制 (1) 字段或 8 位字段更快?

sql - 查找并替换列中的特定字符串

sql-server-2008 - 如何获得时间 (hh :mm:ss) from sql query?

ios - Swift 将数据从 appDelegate 传递到另一个类

excel - 根据条件从范围中选择单元格值

jquery - 如何向Jquery中的每个函数发送参数

c - 如何在c的main函数中声明结构体变量?

VBA Excel双如果