We would like to compare a date from the db with current date.
Here is what I have tried so far:
'Obtain current date
Dim curdate As String = Now.ToString("yyyy")
'Now compare curdate with date from db called eventdate. Event date is of dateTime datatype.
If drv("eventdate").ToString = "" And Year(drv("eventdate").ToString) = curdate Then
'Then do some processing
End if
When I run this code, I get following error:
Conversion from string "" to type 'Date' is not valid.
Please help!
Thank you very much experts.
If Today.CompareTo(CDate(drv("eventdate")).Date) = 0 Then
'Do something
End If
I'm making the assumption here that you only care about the day, and not the time. Otherwise, the odds of having a match within a given day would be about 1 in 2.5 million.
Based on the comment:
If Today.Year.CompareTo(CDate(drv("eventdate")).Year) = 0 Then
'Do something
End If
or
If Today.Year = CDate(drv("eventdate")).Year Then
'Do something
End if
And one more thing: it really sounds like this is a check that should be done by your database. Make it part of the query that returns the results. This will be much faster, and it's where that kind of check belongs. All you'd need is add a check to your where clause like so:
Year(eventdate) = Year(current_timestamp)
If drv has an instance of DataReader then verify DBNull.
IF Not drv.IsDBNull(column_index_of_eventdate) Then
...
If drv.GetDateTime(column_index).Year=Date.Now.Year Then
...
End If
End If
I believe you have either a null or empty value, also your comparisn is wrong, try:
If drv("eventdate").ToString <> "" Andalso Year(drv("eventdate").ToString) = curdate Then
'Then do some processing
End if
Related
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.
Is it possible to check if a named field is within a record set?
EG id, field1, field2, field3 have been selected. Is it possible for VBScript to detect if field2 has been selected. I am also hoping this is possible without looping
Please assume I dont know, nor can see the actual SELECT. I need to detect this after the query has been executed.
This is how its done using a loop, I am also hoping this is possible without looping:
dim rs,field,foundField
sql = "SELECT * from table;"
set rs = conn.execute(sql)
For Each field in rs.Fields
if field.Name = "someFieldName" then
foundField = true
exit for
else
foundField = false
end if
next
TYIA
I use a similar function (in VB6) to the one proposed by bfavaretto... I'm curious why the OP says it doesn't work?
Public Function FieldExists(ByVal rs As Recordset, ByVal fieldName As String) As Boolean
On Error GoTo merr
FieldExists = rs.Fields(fieldName).name <> ""
Exit Function
merr:
FieldExists = False
End Function
This function works for me... and it doesn't return false negatives as far as I know. Also, it appears to be faster than executing a loop for fields that are included in the collection; for fields that are actually missing, the execution times of both methods seems to be equivalent.
EDIT
For VBScript, the above function would look like this:
Function FieldExists(ByVal rs, ByVal fieldName)
On Error Resume Next
FieldExists = rs.Fields(fieldName).name <> ""
If Err <> 0 Then FieldExists = False
Err.Clear
End Function
And the code posted in the question would look like:
dim rs,field,foundField
sql = "SELECT * from table;"
set rs = conn.execute(sql)
foundField = FieldExists(rs, "someFieldName")
I think you need the loop. Found this on MSDN (emphasis mine):
Most of the ASP built-in objects provide collections. Collections are
data structures similar to arrays that store strings, numbers, objects
and other values. Unlike arrays, collections expand and contract
automatically as items are retrieved or stored. The position of an
item will also move as the collection is modified. You can access an
item in a collection by its unique string key, by its index (position)
in the collection, or by iterating through all the items in the
collection.
In any case, you could try this (untested):
dim rs,field,foundField
sql = "SELECT * from table;"
set rs = conn.execute(sql)
if rs.Fields("someFieldName") then
' ... if this doesn't crash, it may return
' false negatives for columns containing null or 0
end if
Here is a record set.
...
Set adoCommand = CreateObject("ADODB.Command")
Set adoConnection = CreateObject("ADODB.Connection")
...
adoCommand.CommandText = strQuery
Set adoRecordset = adoCommand.Execute
And I need to check this recordset has some value or not.
If adoRecordset.Fields("userid").Value Then
'do something...
Else
'do something...
End If
I just tried to check but this code makes occurs an error.
(The Error message below is translated by Google)
ADODB.Recordset Error '800a0cc1'
Item cannot be found in the collection corresponding to the requested name or ordinal
If possible, I want to use Ternary operator.
I don't know which part is wrong.
userid = adoRecordset.Fields("userid").Value ? adoRecordset.Fields("userid").Value : sw
Please understand that I'm a very newbie to asp, thank you.
You need to check for the existence of any rows in the resultset before attempting to access them by name:
If adoRecordset.eof Then
'//no rows
else
'//
There is no ternary operator in VBScript.
Try following example:
if adoRecordset.EOF Then
REM do something
else
REM do something
end if
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
Why does the following code:
A = not IsDBNull(CurRow("BuyBook")) AndAlso CType(CurRow("BuyBook"), string) = "Yes"
results in the following error:
Conversion from type 'DBNull' to type 'String' is not valid.
When AndAlso is supposed to short-circuit according to this article:
http://support.microsoft.com/kb/817250
You are correct. AndAlso is short circuiting.
However, the error comes by calling CurRow("GuyBook") (verify this in a debugger to make sure I'm not a liar or making some crazy assumptions or just misremembering* ;-). Before you ask for a value, you need to ask the DataRow if it has a value. That is, use:
CurRow.IsNull("BuyBook")
Happy coding.
*One should just be able to compare with DBNull.Value or use IsDBNull. However, I am fairly certain that I ran into a row before that threw these exceptions instead of returning a DBNull object. Start by finding out -- in the Immediate Window of the Debugger -- exactly which expression throws the exception.
Have you tried comparing like this:
If CurRow("BuyBook") Is DBNull.Value Then
'...
End If
Instead of not IsDBNull(CurRow("BuyBook")), use NOT (CurRow("BuyBook")) is System.Dbnull.Value). Try this:
A = (NOT (CurRow("BuyBook")) is System.Dbnull.Value) AndAlso CType(CurRow("BuyBook"), string) = "Yes"
OR
A = not string.IsNullOrEmpty(CurRow("BuyBook")) AndAlso CType(CurRow("BuyBook"), string) = "Yes"
If dt.Rows(0)("BuyBook") = DBNull.Value Then
End If
Hope it helps.
In vb.net I usually do something like this:
A = (CurRow("BuyBook") & "" = "Yes")
Old trick from vb6 era. If CurRow("BuyBook") is null, vb.net will consider it as empty string when concatenating it with another string.