VBA How do you pass DATE as parameter to stored procedure - vba

Currently I pass the date parameter as varchar and convert because I got errors with passing a date parameter. I still get errors but its a conversion parameter.
Sub GetPositions() 'xdate As Date
Dim sSQL As String
Dim rs As ADODB.Recordset
Dim cn As ADODB.Connection
Dim cmd As ADODB.Command
Dim prm As ADODB.Parameter
Set cmd = New ADODB.Command
Set prm = New ADODB.Parameter
Sheets("Positions").Select
Range("a2:bb999999").ClearContents
Set cn = New ADODB.Connection
cn.CommandTimeout = 300000
cn.Open "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=True;Initial Catalog=GlobalR;Data Source=SWP"
Dim d As Date
d = "2013/12/03"
cmd.ActiveConnection = cn
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "Get9599Delta"
cmd.NamedParameters = True
Set prm = cmd.CreateParameter("#date", adVarChar, adParamInput, 12)
cmd.Parameters.Append prm
cmd.Parameters("#date").Value = "'12/3/2013'"
Set rs = New ADODB.Recordset
rs.Open cmd.Execute ''''I AM GETTING AN ERROR ON THIS LINE THAT READS
''''''''''' CONVERSION FAILED WHEN CONVERTING DATETIME TO CHARACTER STRING
Cells(2, 1).CopyFromRecordset rs
rs.Close
Set rs = Nothing
cn.Close
Set cn = Nothing
End Sub
here is my stored proc
alter PROC Get9599Delta (#date varchar(12))
AS
DECLARE #d DATETIME
SET #d = CONVERT(DateTime, #date, 104) --convert the varchar to a date
Any idea why I am having this conversion issue?

I'm using Excel 2016 MSO (16.0.8730.2175) 64-bit and my "VBAProject" is referencing "Microsoft ActiveX Data Objects 6.1 Library". I'm running SQL Server Express (64-bit) version 11.0.3156.0 (2012).
My SQL Server database stored procedure has a date parameter with a datetime data type. The stored procedure does not contain SET NOCOUNT ON.
Here's (an edited version of) my code:
Sub ExecuteStoredProcedure(date_ As Date)
Dim connection_ As New ADODB.Connection
connection_.Open "Provider=SQLOLEDB;Data Source=.\SQLEXPRESS;Initial Catalog=not_my_real_database_name;Integrated Security=SSPI"
Dim command_ As New ADODB.Command
With command_
.ActiveConnection = connection_
.CommandType = adCmdStoredProc
.CommandText = "dbo.NotMyRealProcedureName"
.Parameters.Append .CreateParameter("#Date", adDBDate, adParamInput, , date_)
.Execute
End With
End Sub
If you're having similar problems, try commenting or removing all of the code after the connection_.Open ... call. I definitely had problems because of the connection string passed to that call and the error info shown by VBA is so minimal that it was not immediately obvious that my problem wasn't related to the date parameter in my VBA code.

The problem was solved by putting SET NOCOUNT ON at the top of my stored procedure!

try this:
.Parameters.Append .CreateParameter("#date", adDate, adParamInput, , )
# is optional
msdn ( command.CreateParameter (Name, Type, Direction, Size, Value) )
and type of parameter adDBTimeStamp

Related

Insert Into Table from Excel via VB button to stored procedure with Variables

I have a simple table AMC_GW_TESTTABLE with two columns, name nvarchar(20) and phone nvarchar(12). I also have a simple stored procedure with two variables.
create procedure AMC_GW_TESTSP (#name nvarchar(20),
#phone nvarchar(12)) as
insert into AMC_GW_Testtable (name,phone)
values (#name, #Phone)
I have been able to get a button in Excel to create the command:
exec dbo.amc_gw_testsp 'fred' '620-555-1212'
But it does not execute it. I copy this to my SSMS exactly like it and execute it and it works fine. Any ideas?
VBA code
Sub Button1_Click()
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim connStr As String
Dim param As ADODB.Parameter
Dim param2 As ADODB.Parameter
connStr = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;" _
& "Initial Catalog=am_app);Data Source=bcu-sql-01"
Set conn = New ADODB.Connection
conn.ConnectionString = connStr
conn.Open
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = conn
.CommandType = adCmdStoredProc
.CommandText = "AMC_GW_TESTSP"
Set param = .CreateParameter("#name", adVarChar, adParamInput, 20, "Christopher")
.Parameters.Append param
Set param2 = .CreateParameter("#phone", adVarChar, adParamInput, 12, "0123456789")
.Parameters.Append param
.Execute
End With
conn.Close
Set cmd = Nothing
Set conn = Nothing
End Sub
I hope I did not scare you with a request for VBA Code
To give you an idea of what you should have:
Sub Button1_Click()
Dim conn As ADODB.Connection
Dim cmd As ADODB.Command
Dim connStr As String
Dim param As ADODB.Parameter
Dim param2 As ADODB.Parameter
connStr = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;" & _
"Initial Catalog=dbname;Data Source=servername"
Set conn = New ADODB.Connection
conn.ConnectionString = connStr
conn.Open
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = conn
.CommandType = adCmdStoredProc
.CommandText = "AMC_GW_TESTSP"
Set param = .CreateParameter("#name", adVarChar, adParamInput, 20, "Christopher")
.Parameters.Append param
Set param2 = .CreateParameter("#phone", adVarChar, adParamInput, 12, "0123456789")
.Parameters.Append param
.Execute
End With
conn.Close
Set cmd = Nothing
Set conn = Nothing
End Sub
Things that you will have to change. Firstly the connection string (connStr). You will need to provide database name in place of dbname and server in place of servername. Also this string is assuming that you are using Windows Authentication for your SQL Server. If not you need to remove Integrated Security=SSPI; and in its place supply User ID=myUser;Password=myPassword;.
Next you will notice that the last parameter in the .CreateParameter function is a fixed string ("Christopher" and "0123456789"). In your case, they should be variables taken from cells in the spreadsheet. Please, please make sure that these strings do not contain ";" before trying to Execute.
I hope this helps, but feel free to contact me, if anything is less than clear!
PS You will need to make sure under Tools References, that you have the highest version of Microsoft ActiveX Data Objects Library checked (mine is 6.1, but anything 2.0 or higher definitely works).

Type Conversion Errors with DateTime

I am trying to add data to a SQL database column which called 'ModifiedDate' and is of type 'DateTime', using the following code:
Dim fso As FileSystemObject
Dim dteModifiedDate As Date
Dim cm As ADODB.Command
Dim cn As ADODB.Connection
Set fso = New FileSystemObject
Set cm = New ADODB.Command
Set cn = New ADODB.Connection
cn.CursorLocation = adUseClient
cn.ConnectionString = strDBConnectionString
cn.Open
Set cm.ActiveConnection = cn
dteModifiedDate = fso.GetFile("C:\TestFile.txt").DateLastModified
cm.Parameters.Append cm.CreateParameter("#ModifiedDate", adDBDate, adParamInput, , dteModifiedDate)
cm.CommandText = "SELECT CAST('#ModifiedDate' as DateTime) FROM MainData"
cm.CommandType = adCmdText
cm.Execute
The problem is that when I run this, the code breaks on the execute statement with this error:
Run-time error -2147217913 (80040e07)
conversion failed when converting date and/or time from character string.
I have tried several different 'Type's for the command (adDate,adDBTimestamp,adWChar etc...) but get errors regarding conversion between data types.
What data type do you use for this? Obviously I need to be able to get the parameter data type correct with a type that is compatible with the SQL table data type.
You don't need to specify the length of the date. Also adDate should be fine:
cm.Parameters.Append cm.CreateParameter("#ModifiedDate", adDate, adParamInput, , dteModifiedDate)

ODBC SQL Server Driver - Conversion failed when converting date and/or time from character string

I am using MS Access VBA to call a stored procedure with paramters passed from Access. I am having issues passing my date variables to the SQL Server Stored procedure:
VBA:
Dim zsql, asql, bsql, gsql As String
Dim searchDeal, searchReviewed As String
Dim searchDate, searchFile As Date
Dim searchType As String
Dim user As String
Dim qdfNew As DAO.QueryDef
Dim myRecordset6 As DAO.Recordset
Dim myDatabase6 As DAO.Database
Dim mycheckRs As DAO.Recordset
DoCmd.SetWarnings False
searchDeal = Me.cboDeal.Value
searchDate = Me.cboStDate.Value
searchFile = Me.cboFile.Value
user = GetUser()
Dim dbconn As New ADODB.Connection
Dim cmd As New ADODB.Command
Dim rs As New ADODB.Recordset
Dim param As New ADODB.Parameter
'' Connect to Data Source - Securities DB - SQL Server
Set dbconn = New ADODB.Connection
dbconn.ConnectionString = "driver=SQL Server;server=R7SQL1;database=SecuritiesDB;trusted_connection=YES"
dbconn.Open dbconn.ConnectionString
Set cmd = New ADODB.Command
cmd.ActiveConnection = dbconn
'' Set CommandText equal to the stored procedure name (spStatementCheck)
cmd.CommandType = adCmdStoredProc
cmd.CommandText = "spAppendActivity"
''cmd.NamedParameters = True 'paramStatementCheck'
cmd.Parameters.Append _
cmd.CreateParameter("#SPstrNGN", adVarChar, adParamInput, 25, searchDeal)
cmd.Parameters.Append _
cmd.CreateParameter("#SPuser", adVarChar, adParamInput, 100, user)
cmd.Parameters.Append _
cmd.CreateParameter("#SPdDateActivity", adDBTimeStamp, adParamInput, 10, searchDate) <--ISSUE
cmd.Parameters.Append _
cmd.CreateParameter("#SPdDateFile", adDBTimeStamp, adParamInput, 10, searchFile) <--ISSUE
--Date format that I am passing should be MM/DD/YYYY
rs.CursorType = adOpenDynamic
rs.CursorLocation = adUseClient
rs.LockType = adLockOptimistic
rs.Open cmd
SQL:
ALTER PROCEDURE [dbo].[spAppendActivity]
#SPsearchDeal as nvarchar(25),
#SPsearchDate as datetime,
#SPsearchFile as datetime,
#SPuser as nvarchar(100)
AS
-- SET NOCOUNT ON added to prevent extra result sets from
-- interfering with SELECT statements.
SET NOCOUNT ON;
-- Insert statements for procedure here
delete from tbl_Activity_Losses;
INSERT into tbl_Activity_Losses ([Date], NGN_Short, FileDate)
Select [Date], NGN_Short, Filedate
from tbl_Master_Rec
where tbl_Master_Rec.[Date] = #SPsearchDate <--Conversion Issue
and tbl_Master_Rec.FileDate = #SPsearchFile <--Conversion Issue
and tbl_Master_Rec.NGN_Short like '%' + #SPsearchDeal + '%'
I get the following error message when the Date is passed using the adDBTimeStamp "[Microsoft][ODBC SQL Server Driver] Conversion failed when converting date and/or time from character string."
I have also tried passing the date as adDBDate and get the error "[Microsoft][ODBC SQL Server Driver] Optional Feature Not Implemented. "
Please let me know if you need more information on the issue I am having
Please note that you will need to construct the datetime string in this format:
adDBDate
Indicates a date value (yyyymmdd) (DBTYPE_DBDATE).
adDBTimeStamp
Indicates a date/time stamp (yyyymmddhhmmss plus a fraction in billionths) (DBTYPE_DBTIMESTAMP).
adDBDate and adDBTimeStamp

VBA passing date in stored procedure problems

I'm having difficulty passing a Date value to a datetime value using a SQL Stored Procedure. The #DateTime parameter is in datetime format in MyDb in a Microsoft SQL Server. When I run the below subroutine, I get an error: Parameter type not supported. I believe the error has to do with with the adDBTimeStamp parameter type. Any idea how to resolve this problem?
Public Sub AddDateTime
Dim DateTime as Date
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim param as ADODB.Parameter
Dim sConnString As String
/*Create the connection string*/
DateTime = Now()
sConnString = "Driver={SQL Server};Server=TheServer3;Database=MyDb;Trusted_Connection=Yes;"
Set rs = New ADODB.Recordset
Set cmd = New ADODB.Command
cmd.ActiveConnection = sConnString
cmd.CommandText = "usp_AddNewDateTime"
cmd.CommandType = adCmdStoredProc
Set param = cmd.CreateParameter("#DateTime", adDBTimeStamp, adParamInput, , DateTime)
cmd.Parameters.Append param
Set rs = cmd.Execute
/*Clean up*/
Set conn = Nothing
Set rs = Nothing
End Sub
Since you are providing a Date value, just use adDBDate:
Set param = cmd.CreateParameter("#DateTime", adDBDate, adParamInput, , DateTime)
Simple solution -- The DateTime variable has to be converted to a Double: CDbl(DateTime)

Excel VBA executing SQL Server stored procedure - result set throwing error 3704

I am trying to execute a SQL Server stored procedure from Excel VBA. The procedure returns rows into a result set object. However, while running the code, it throws an error:
3704 Operation is not allowed when the object is closed
Note:
There is no problem with the database connection because Select query running on the same connection object are working fine.
Dim cn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim cmd As ADODB.Command
Dim prm As ADODB.Parameter
Dim rst As New ADODB.Recordset
Set cn = New ADODB.Connection
Set cmd = New ADODB.Command
ThisWorkbook.initialize
cn.Provider = "sqloledb"
cn.Properties("Data Source").Value = ThisWorkbook.server
cn.Properties("Initial Catalog").Value = ThisWorkbook.db
cn.Properties("User ID").Value = "xxxxx"
cn.Properties("Password").Value = "xxxxx"
cn.Open
Set cmd = New ADODB.Command
cmd.CommandText = "Generate_KPI_Process_Quality_Check_RunTime"
cmd.CommandType = adCmdStoredProc
cmd.ActiveConnection = cn
Set prm = cmd.CreateParameter("#currentMonth", adChar, adParamInput, 255, cmb_month.Value)
cmd.Parameters.Append prm
Set prm = cmd.CreateParameter("#center", adChar, adParamInput, 255, cmb_center.Value)
cmd.Parameters.Append prm
rst.CursorType = adOpenStatic
rst.CursorLocation = adUseClient
rst.CursorLocation = adUseServer
rst.LockType = adLockOptimistic
rst.Open cmd
If (rst.BOF And rst.EOF) Then
'Some Code
End If
Put
SET NOCOUNT ON
in the stored procedure -- this will prevent output text generation like "1 record(s) updated".
You have to provide more parameters for the Open method of Recordset Object
try rst.Open cmd, cn
Use the Set keyword to assign the object:
Set cmd.ActiveConnection = cn
otherwise, the default property of the Connection object (which happen to be the connection string) will be assigned in lieu of the Connection object itself.
Just put another recordset that will contain resultsets
Dim rst1 As New ADODB.Recordset
SET rst1=rst.NextRecordset 'this will return the first resultset
If rst1.BOF or rst1.EOF Then...
'some code
End If