Monday, March 26, 2012

No Date passed

I want to update a record that has a datetime field in it. But what if there is no parameter given for that field, i.e. what is the correct type/value to pass as parameter?

Example: A DOB field for a user profile, but the user doesn't enter his birthday

This is some example code that I use to update:


Private Sub UpdateDOB(ByVal dob As Date)

Dim parameters As SqlParameter() = { _
New SqlParameter("@.Birthday", SqlDbType.DateTime, 8)}

parameters(0).Value = dob

'Run Stored Procedure


This gives me the exception "SqlDateTime overflow. Must be between 1/1/1753 12:00:00 AM and 12/31/9999 11:59:59 PM" when I don't pass a valid date. I tried passingNothing but same error (in this case it convert dob to "#12:00:00 AM#")

The only thing I can think of is to use Date.MaxValue and then check in application logic, but there must be a better way!use dbnull.value

hth|||ndinakar, I tried this:

User.DOB = System.DBNull.Value

but then I get an error, DBNull.Value cannot be converted to Type Date
how should i assign DBNull.Value ?|||Instead of passing DOB as date pass it as string


Private Sub UpdateDOB(ByVal strDOB As string)
...
cmd.Parameters.Add(New SqlParameter("@.Birthday", SqlDbType.DateTime))

If (strDOB= "") Then
cmd.Parameters("@.Date").Value = sqldatenull
'cmd.Parameters("@.Date").Value = DBNull.Value
Else
cmd.Parameters("@.Date").Value = DateTime.Parse(strDOB)
End If

HTH|||or this :


myCommand.Parameters.Add(New SqlParameter("@.cusbday",SqlDbType.datetime))
If len(trim(bday.Text)) = 0 Then
myCommand.Parameters("@.cusbday").Value = SqlDateTime.null
Else
myCommand.Parameters("@.cusbday").Value = server.htmlencode(DateTime.Parse(bday.Text))
End If

you need to import system.data.sqldypes namespace.

hth|||Thank you

SqlDateTime.Null worked fine as parameter.sql

No comments:

Post a Comment