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)
Related
I'm trying up date an SQL table (Date field) with a date cell in excel and getting an error
Error #-2147217913: Operand type clah int is incompatible with Date
Connection to the database is fine.
This is the code i'm using
Private Sub CommandButton1_Click()
On Error GoTo FormLoadError
Dim conn As ADODB.Connection
Dim rs As ADODB.Recordset
Dim sConnString As String
Dim FromDate As Date
Dim ToDate As Date
Dim FromNumber As String
Sheet2.Range("a2:zz9999").ClearContents
' Create the connection string.
sConnString = "Provider=SQLOLEDB;Data Source=SQL;" & _
"Initial Catalog=M2MTECLIVE;" & _
"Integrated Security=SSPI;"
' Create the Connection and Recordset objects.
Set conn = New ADODB.Connection
Set rs = New ADODB.Recordset
' Open the connection and execute.
conn.Open sConnString
FromDate = Worksheets("Parameters").Range("b4") 'Cell be contains a date in the format YYYY-MM-DD
Set rs = conn.Execute("update dbo.M2MDates set FD = " & FromDate)
conn.Close
Any ideas ?
Consider using ADO parameters via ADO command object which avoids need of concatenating and punctuating values to SQL statement:
conn.Open sConnString
' PREPARED STATEMENT WITH QMARKS ?
strSQL = "update dbo.M2MDates set FD = ?"
FromDate = Worksheets("Parameters").Range("b4")
Set cmd = New ADODB.Command
With cmd
.ActiveConnection = conn
.CommandText = strSQL
.CommandType = adCmdText
' BIND DATE PARAMETER
.Parameters.Append .CreateParameter("date_prm", adDate, adParamInput, , FromDate)
' EXECUTE ACTION QUERY (NO RECORDSET)
.Execute
End With
conn.Close
Set cmd = Nothing: Set conn = Nothing
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)
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
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
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