Jump to content
Xtreme .Net Talk

Recommended Posts

Posted

I like using store procedures because it allows me to specify what the format of my values are going to be ahead of time however, the SQL command SELECT GetDate does not have this option.

 

Below is how I solved it, and I am looking for advice as to whether or not it is a good technique or if there is something more elegant:

 

Particularly of interest: Do I need to cast the CurrentDateTime to a DateTime object, or should the SqlDataReader already be returning it in this format?

DateTime sqlTime;
try {
 m_db.Open;
 using (SqlCommand cmd = new SqlCommand("SELECT GetDate AS [CurrentDateTime]", m_db)) {
   SqlDataReader r = cmd.ExecuteReader();
   while (r.Read() == true) {
     sqlTime = (DateTime)r["CurrentDateTime"];
   }
 }
} catch (InvalidOperationException e) {
 Console.WriteLine(e.StackTrace);
 sqlTime = DateTime.Now;
} catch (SqlException e) {
 Console.WriteLine(e.StackTrace);
 sqlTime = DateTime.Now;
} finally {
 m_db.Close();
}

  • Administrators
Posted

You could always use the datareader's IsDbNull function to check for nulls before attempting to assign the value, or if you are using .Net 2 or higher then the sqlTime variable could be defined as a nullable datetime.

 

       DateTime sqlTime;

           //  m_db.Open;
           using (SqlCommand cmd = new SqlCommand("SELECT GetDate AS [CurrentDateTime]"))
           {
               SqlDataReader r = cmd.ExecuteReader();
               while (r.Read() == true)
               {
                   if (!r.IsDBNull(0))
                       sqlTime = (DateTime)r["CurrentDateTime"];
               }
           }

or

       DateTime? sqlTime;

           //  m_db.Open;
           using (SqlCommand cmd = new SqlCommand("SELECT GetDate AS [CurrentDateTime]"))
           {
               SqlDataReader r = cmd.ExecuteReader();
               while (r.Read() == true)
               {
               sqlTime = (DateTime)r["CurrentDateTime"];
               }
           }

Posting Guidelines FAQ Post Formatting

 

Intellectuals solve problems; geniuses prevent them.

-- Albert Einstein

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...