I have two values that have dates inside in the format dd/MM/yyyy and am trying to get the dates in between these two values. The values look like these(17/06/2013) in ONE and TWO variables. And then I send from my asp to an oracle procedure to execude a query and i get ORA-01843 not a valid month. Ive searched for this error but none of the solutions seemed to work for me. The thing is that this code used to work, I didnt change anything on these code and now it doesnt work for some reason.
Here is the code from my asp:
ONE = fromDate.Value
TWO = toDate.Value
Generic.searchBetweenDates(ONE, TWO, dt)
Public Function searchBetweenDates(ByVal PFROMDATE As String, ByVal PTODATE As String, ByRef PUSERINFO As DataTable)
Dim myDataTable As New DataTable
Dim myDataAdapter As New OracleDataAdapter
Dim oraCmd As New OracleCommand("cantine_test.searchbetweendates")
oraCmd.CommandType = System.Data.CommandType.StoredProcedure
oraCmd.Parameters.Add(New OracleParameter("PFROMDATE", OracleType.VarChar, 30)).Value = PFROMDATE
oraCmd.Parameters.Add(New OracleParameter("PTODATE", OracleType.VarChar, 300)).Value = PTODATE
oraCmd.Parameters.Add(New OracleParameter("PUSERINFO", OracleType.Cursor)).Direction = ParameterDirection.Output
Dim oConn As New OracleConnection(ConnectionString)
Try
oConn.Open()
oraCmd.Connection = oConn
cleanParams(oraCmd.Parameters)
myDataAdapter.SelectCommand = oraCmd
myDataAdapter.Fill(myDataTable)
If Not myDataTable Is Nothing Then
PUSERINFO = myDataTable 'return reference using byref param
End If
Catch ex As Exception
MsgBox(ex.Message)
Finally
oraCmd.Dispose()
oConn.Close()
myDataAdapter.Dispose()
End Try
Return PUSERINFO
End Function
And here is the code from my Oracle procedure:
PROCEDURE searchbetweendates
(PFROMDATE IN VARCHAR2, PTODATE IN VARCHAR2, PUSERINFO OUT SYS_REFCURSOR)
AS
BEGIN
OPEN PUSERINFO FOR
SELECT ORDERDATE,ORDERID,ORDERTIME,ORDERLIST,QUANTITY,ITEMPRICE,ORDERPRICE,LOCATION
FROM ORDERSDETAIL
WHERE ORDERDATE >= to_date(PFROMDATE, 'dd/MM/yyyy')
AND ORDERDATE <= to_date(PTODATE,'dd/MM/yyyy');
END;
Any ideas?
Oracle hurls ORA-01843 when we pass a string which doesn't match the specified date format: for instance when the string has the US format and the format mask doesn't:
SQL> select to_date('01/13/2013', 'dd/mm/yyyy') from dual
2 /
select to_date('01/13/2013', 'dd/mm/yyyy') from dual
*
ERROR at line 1:
ORA-01843: not a valid month
SQL>
So, the most likely explanation is that you are passing values which you think have a common format but in fact don't. This is fantastically common when "dates" are stored as strings. In other words, this is a debugging question.
Although, one thought occurs: is ORDERSDETAIL.ORDERDATE itself of a DATE datatype.
#6/17/2013#{Date} is the sort of string which will definitely lead to an ORA-1843 error. So you need to trace your code to discover where it comes from.
"how should i check if the value in my columns are correct"
Debugging dot Net is not my strong point. However, there are traditionally two ways. One is to step through the code in a debugging tool. If you're using Visual Studio or a similar IDE you should be able to do this. The other suggestion is to embed logging commands in your code and write trace messages e.g. to a file.
Which approach suits you best? Only you can tell.
Related
I have a query called qryAlloc_Source that has two paramaters under one criteria:
>=[forms]![frmReportingMain]![txtAllocStart] And <=[forms]![frmReportingMain]![txtAllocEnd])
A have a separate query that ultimately references qryAlloc_Source (there are a couple queries in between), and that query runs fine when I double click it in the UI, but if I try to open it in VBA, I get an error. My code is:
Dim rst As Recordset
Set rst = CurrentDb.OpenRecordset("qryAlloc_Debits")
I am getting run-time error 3061, Too few parameters. Expected 2. I've read that I may need to build out the SQL in VBA using the form parameters, but it would be pretty complex SQL given that there are a few queries in the chain.
Any suggestions as to a workaround? I considered using VBA to create a table from the query and then just referencing that table--I hate to make extra steps though.
The reason you get the error when you just try to open the recordset is that your form is not open and when you try to access [forms]![frmReportingMain] it's null then you try to get a property on that null reference and things blow up. The OpenRecordset function has no way of poping up a dialog box to prompt for user inputs like the UI does if it gets this error.
You can change your query to use parameters that are not bound to a form
yourTableAllocStart >= pAllocStart
and yourTableAllocEnd <= pAllocEnd
Then you can use this function to get the recordset of that query.
Function GetQryAllocDebits(pAllocStart As String, pAllocEnd As String) As DAO.Recordset
Dim db As DAO.Database
Dim qdef As DAO.QueryDef
Set db = CurrentDb
Set qdef = db.QueryDefs("qryAlloc_Debits")
qdef.Parameters.Refresh
qdef.Parameters("pAllocStart").Value = pAllocStart
qdef.Parameters("pAllocEnd").Value = pAllocEnd
Set GetQryAllocDebits = qdef.OpenRecordset
End Function
The disadvantage to this is that when you call this now on a form that is bound to it it doesn't dynamically 'fill in the blanks' for you.
In that case you can bind forms qryAlloc_debts and have no where clause on the saved query, then use the forms Filter to make your where clause. In that instance you can use your where clause exactly how you have it written.
Then if you want to still open a recordset you can do it like this
Function GetQryAllocDebits(pAllocStart As String, pAllocEnd As String) As DAO.Recordset
Dim qdef As DAO.QueryDef
Set qdef = New DAO.QueryDef
qdef.SQL = "Select * from qryAlloc_Debits where AllocStart >= pAllocStart and pAllocEnd <= pAllocEnd"
qdef.Parameters.Refresh
qdef.Parameters("pAllocStart").Value = pAllocStart
qdef.Parameters("pAllocEnd").Value = pAllocEnd
Set GetQryAllocDebits = qdef.OpenRecordset
End Function
While a [Forms]!... reference does default to a form reference when a QueryDef is run from the GUI, it is actually just another Parameter in the query in VBA. The upshot is you don't have to recode your query/create a new one at all. Also, as #Brad mentioned, whether a parameter is in the final query of a chain of queries or not, you are able to refer to the parameter as if it is in the collection of the final query. That being the case, you should be able to use code similar to this:
Sub GetQryAllocDebits(dteAllocStart As Date, dteAllocEnd as Date)
Dim db As DAO.Database
Dim qdf As DAO.QueryDef
Dim rst As DAO.Recordset
Set db = CurrentDb()
Set qdf = db.QueryDefs("qryAlloc_Debit")
If CurrentProject.AllForms("frmReportingMain").IsLoaded Then
qdf.Parameters("[forms]![frmReportingMain]![txtAllocStart]") = [forms]![frmReportingMain]![txtAllocStart]
qdf.Parameters("[forms]![frmReportingMain]![txtAllocEnd]") = [forms]![frmReportingMain]![txtAllocEnd]
Else
qdf.Parameters("[forms]![frmReportingMain]![txtAllocStart]") = CStr(dteAllocStart)
qdf.Parameters("[forms]![frmReportingMain]![txtAllocEnd]") = CStr(dteAllocEnd)
End If
Set rst = qdf.OpenRecordset
Do Until rst.EOF
'...do stuff here.
Loop
Set rst = Nothing
Set qdf = Nothing
Set db = Nothing
End Function
If the referenced form is open, the code is smart enough to use the referenced controls on the form. If not, it will use the dates supplied to the subroutine as parameters. A gotcha here is that the parameters did not like when I set them as date types (#xx/xx/xx#), even if the field were dates. It only seemed to work properly if I set the params as strings. It didn't seem to be an issue when pulling the values straight out of the controls on the forms, though.
I know it's been a while since this was posted, but I'd like to throw in my tuppence worth as I'm always searching this problem:
A stored query can be resolved:
Set db = CurrentDb
Set qdf = db.QueryDefs(sQueryName)
For Each prm In qdf.Parameters
prm.Value = Eval(prm.Name)
Next prm
Set rst = qdf.OpenRecordset
For SQL:
Set db = CurrentDb
Set qdf = db.CreateQueryDef("", "SELECT * FROM MyTable " & _
"WHERE ID = " & Me.lstID & _
" AND dWeekCommencing = " & CDbl(Me.frm_SomeForm.Controls("txtWkCommencing")) & _
" AND DB_Status = 'Used'")
For Each prm In qdf.Parameters
prm.Value = Eval(prm.Name)
Next prm
Set rst = qdf.OpenRecordset
This assumes that all parameter values are accessible - i.e. forms are open and controls have values.
'I have two parameters in my recordset and I was getting the "Too few parameters. Expected 2" 'error when using an OpenRecordset in MS Access vba, and this is how I got around it and IT WORKS! see the below sub routine:
'Private Sub DisplayID_Click()
'1. I created variables for my two parameter fields xEventID and xExID as seen below:
Dim db As Database
Dim rst As Recordset
Dim xEventID As Integer
Dim xExId As Integer
'2. Sets the variables to the parameter fields as seen below:
Set db = CurrentDb
xEventID = Forms!frmExhibitorEntry!txtEventID
xExId = Forms!frmExhibitorEntry!subExhibitors!ExID
'3. Set the rst to OpenRecordSet and assign the Set the variables to the WHERE clause. Be sure to include all quotations, ampersand, and spaces exactly the way it is displayed. Otherwise the code will break!exactly as it is seen below:
Set rst = db.OpenRecordset("SELECT tblInfo_Exhibitor.EventID,tblInfo_Display.ExID, tblMstr_DisplayItems.Display " _
& "FROM tblInfo_Exhibitor INNER JOIN (tblMstr_DisplayItems INNER JOIN tblInfo_Display ON tblMstr_DisplayItems.DisplayID = tblInfo_Display.DisplayID) ON tblInfo_Exhibitor.ExID = tblInfo_Display.ExID " _
& "WHERE (((tblInfo_Exhibitor.EventID) =" & xEventID & " ) and ((tblInfo_Exhibitor.ExID) =" & xExId & " ));")
rst.Close
Set rst = Nothing
db.Close
'End Sub
I am trying to call a PL/SQL procedure which has an output value from a Visual Basic 6 function, but it does not work.
Here my code.
PL/SQL code (so far, it is just a mock):
create or replace
PROCEDURE IS_SINISTRO_ABS_MOCK
( numPol in VARCHAR2,
codGaranzia in VARCHAR2,
res out BOOLEAN
) AS
BEGIN
res := TRUE;
END IS_SINISTRO_ABS_MOCK;
VB6 code:
Private Function IsSinistroInABS(NumPol As String, CodGaranzia As String) As Boolean
Dim dbConn As New ADODB.Connection
With dbConn
.Provider = "OraOLEDB.Oracle"
.Properties("Data Source") = "*********"
.Properties("User Id") = "ROUTING"
.Properties("Password") = "***********"
.Open
End With
Dim dbCmd As ADODB.Command
Dim result As Boolean
Set dbCmd = New ADODB.Command
dbCmd.ActiveConnection = dbConn
dbCmd.CommandTimeout = 300
dbCmd.CommandType = adCmdStoredProc
dbCmd.CommandText = "{CALL ROUTING.IS_SINISTRO_ABS_MOCK(?,?,?)}"
dbCmd.Parameters.Append dbCmd.CreateParameter(, adLongVarChar, adParamInput, _
Len(NumPol), NumPol)
dbCmd.Parameters.Append dbCmd.CreateParameter(, adLongVarChar, adParamInput, _
Len(CodGaranzia), CodGaranzia)
dbCmd.Parameters.Append dbCmd.CreateParameter(, adBoolean, adParamOutput, , _
result)
dbCmd.Prepared = True
dbCmd.Execute
IsSinistroInABS = dbCmd.Parameters("res").value
dbConn.Close
End Function
The DB connection works properly, indeed I succeeded in executing a standard SQL query, but I get an unspecified error when I try to run the procedure. I succeeded also in launching a procedure without any parameters. As a result, the problem is supposed to be in the use of them.
Note that the procedure is a standalone one. In other words, it is not included in any package.
Maybe I'm a bit late (you posted your question 2.5 years ago), but I got the same problem.
After a lot of digging and frustration, I found out the error occurs when the stored procedure has numeric output parameters (VARCHAR is OK as well as any input parameter).
I finally found out that everything works correctly when you use the ancient DB-provider MSDAORA.1.
Im using VB.net to control a DevExpress report object, i currently have a function that handles the data of said report, and when i run it the reports data comes back completely blank. When i run SQL Server Profiler i can see the command exec dbo.sp_Get_CompanyTime #intCompanyID=1,#dteStart=NULL,#dteEnd=NULL,#strUserID=N'',#intCustomerID=1,#intProjectID=1 is ran when the report is called, returning no data at all because there UserID doesnt match anything, same for customer ID and project ID. The problem im facing is that in VB i have
Dim spcomptime As dsReporting.sp_Get_CompanyTimeDataTable = New dsReporting.sp_Get_CompanyTimeDataTable
Dim OpenDate As Nullable(Of DateTime)
Dim CloseDate As Nullable(Of DateTime)
Dim clientId As Nullable(Of Integer)
Dim cusId As Nullable(Of Integer)
Dim proID As Nullable(Of Integer)
Sp_Get_CompanyTimeTableAdapter.Fill(spcomptime, 1, OpenDate, CloseDate, clientId, cusId, proID)
which as you can hopefully see it should be passing null values for everything past the first 2 parameters! ive tried using DBNull.value as suggested elsewhere, but it tells me it cannot be converted to type "Integer?".
Somebody help me i've been trying to solve this for what feels like an age.
I have a FormView where I pull data from one table (MS Access), and then insert it (plus more data) into another table. I'm having issues with the dates.
The first table has two date fields: date_submitted and date_updated. In some records, date_updated is blank. This causes me to get a data mismatch error when attempting to insert into the second table.
It might be because I'm databinding the date_updated field from the first table into a HiddenField on the FormView. It then takes the value from the HiddenField and attempts to insert it into the second table:
Dim hfDateRequestUpdated As HiddenField = FormView1.FindControl("hfDateRequestUpdated")
myDateRequestUpdated = hfDateRequestUpdated.Value
'... It then attempts to insert myDateRequestUpdated into the database.
It works when there is a value there, but apparently you can't insert nothing into a date/time field in Access. I suppose I could make a second insert statement that does not insert into date_updated (to use when there is no value indate_updated), but is that the only way to do it? Seems like there should be an easier/less redundant way.
EDIT:
Okay. So I've tried inserting SqlDateTime.Null, Nothing, and DBNull.Value. SqlDateTime.Null results in the value 1/1/1900 being inserted into the database. "Nothing" causes it to insert 1/1/2001. And if I try to use DBNull.Value, it tells me that it cannot be converted to a string, so maybe I didn't do something quite right there. At any rate, I was hoping that if there was nothing to insert that the field in Access would remain blank, but it seems that it has to fill it with something...
EDIT:
I got DBNull.Value to work, and it does insert a completely blank value. So this is my final working code:
Dim hfDateRequestUpdated As HiddenField = FormView1.FindControl("hfDateRequestUpdated")
Dim myDateRequestUpdated = Nothing
If hfDateRequestUpdated.Value = Nothing Then
myDateRequestUpdated = DBNull.Value
Else
myDateRequestUpdated = DateTime.Parse(hfDateRequestUpdated.Value)
End If
Thanks everyone!
Sara, have you tried casting the date/time before you update it? The data mismatch error likely comes from the fact that the hfDateRequestUpdated.Value you're trying to insert into the database doesn't match the column type.
Try stepping through your code and seeing what the type of that value is. If you find that it's a string (which it seems it might be, since it's coming from a field on a form), then you will need a check first to see if that field is the empty string (VBNullString). If so, you will want to change the value you're inserting into the database to DBNull, which you can get in VB.Net using DBNull.Value.
We can't see your code, so we don't know exactly how you get the value into the database, but it would look something like this
If theDateValueBeingInserted is Nothing Then
theDateValueBeingInserted = DBNull.Value
EndIf
Keep in mind that the above test only works if the value you get from the HiddenField is a string, which I believe it is according to the documentation. That's probably where all this trouble you're having is coming from. You're implicitly converting your date/time values to a string (which is easy), but implicitly converting them back isn't so easy, especially if the initial value was a DBNull
aside
I think what Marshall was trying to suggest was the equivalent of the above code, but in a shortcut expression called the 'ternary operator', which looks like this in VB.Net:
newValue = IF(oldValue is Nothing ? DBNull.Value : oldValue)
I wouldn't recommend it though, since it's confusing to new programmers, and the syntax changed in 2008 from IFF(condition ? trueResult : falseResult)
Your code
Dim myDateRequestUpdated As DateTime
myDateRequestUpdated = DateTime.Parse(hfDateRequestUpdated.Value) : DBNull.Value()
has a couple of problems:
When you declare myDateRequestUpdated to be DateTime, you can't put a DbNull.Value in it.
I'm not sure you need the () for DbNull.Value: it's a property, not a method (I don't know enough VB to say for sure)
VB doesn't know that : operator
What you probably want is a Nullable(Of DateTime) to store a DateTime value that can also be missing.
Then use something like this to store the value:
myDateRequestUpdated = If(String.IsNullOrWhiteSpace(hfDateRequestUpdated.Value),
Nothing, DateTime.Parse(hfDateRequestUpdated.Value))
If hfDateRequestUpdated.Value is empty, then use Nothing as the result; else parse the value as date (which might fail if it is not a valid date!).
Try this:
Protected Sub Button2_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Button2.Click
Dim str As String
If TextBox1.Text.Length <> 0 Then
str = "'" & TextBox1.Text & "'"
Else
str = "NULL"
End If
sql = "insert into test(test1) values(" & str & ")"
dsave_sql(sql)
End Sub
Function save_sql(ByVal strsql As String, Optional ByVal msg As String = "Record Saved Sucessfully") As String
Dim sqlcon As New SqlConnection(strConn)
Dim comm As New SqlCommand(strsql, sqlcon)
Dim i As Integer
Try
sqlcon.Open()
i = CType(comm.ExecuteScalar(), Integer)
save_sql = msg
Catch ex As Exception
save_sql = ex.Message
End Try
sqlcon.Close()
Return i
End Function
This problem has driven me mad for over a day now. I can create a connection to the database, I can execute sql and return results from that but I can't seem to call a stored Procedure. Here is the code
Dim myCMD As New OracleCommand
Dim TheDataReader as New OracleDataReader
myConnection1.Open()
myCMD.Connection = myConnection1
myCMD.CommandType = CommandType.StoredProcedure
myCMD.CommandText = "WS_DATA_LAYER.select_user_groups"
myCMD.Parameters.Add(New OracleParameter("id_user", OracleDbType.VarChar2)).Value = "TXA"
myCMD.Parameters.Add(New OracleParameter("ws_rs", OracleDbType.RefCursor)).Direction = ParameterDirection.Output
' Tried every single execute function here and none have worked
' Either error is thrown or empty refcursor
myCMD.ExecuteScalar()
TheDataReader = myCMD.Parameters(1).Value().GetDataReader()
The Problem lies in ExecuteScalar at the moment. It's throwing an exception called "Input string was not in a correct format". I've tried passing the string with Oracle single quotes and get the same thing. If I use
TheDataReader = myCMD.ExecuteQuery()
it works ok but no results are returned. I've verified that the procedure returns results for the user I'm logged in as. When the query was executing I could see a refcursor in there but it was empty. I must be going mad.
Any help is appreciated
Anyone else that may have this problem, I was passing the OracleDBType.Varchar2 as a parameter to the above VB method. But I had it declared as an integer, it needs to be explicitly passed as an OracleDBType