Click here to Skip to main content
15,889,281 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have a table in SQL called OEETable, it contains amongst other things, RecordID and RecordDate field.

I am trying to retrieve these fields using code below:
C#
//*** Get Record ID ***

SqlCommand readRecID = new SqlCommand();
string sqlReadRecID = "Select max(RecordID) from OEETable";

readRecID.Connection = databaseConnection;
readRecID.CommandText = sqlReadRecID;

SqlDataReader getRecId;

getRecId = readRecID.ExecuteReader();
getRecId.Read();

Int32 recid = getRecId.GetInt32(0);

getRecId.Close();


*** Get Record Date ***

SqlCommand readDate = new SqlCommand();
string sqlReadDate = "Select max(RecordDate) from OEETable";

readDate.Connection = databaseConnection;
readDate.CommandText = sqlReadDate;

SqlDataReader getReadDate;

getReadDate = readDate.ExecuteReader();
getReadDate.Read();

string date = getReadDate.ToString();
getReadDate.Close();

I retrieve the RecordID absolutely fine, but no luck with getting the date.

Any help would be appreciated.
Posted
Updated 5-Apr-12 10:25am
v2
Comments
André Kraak 5-Apr-12 16:25pm    
Edited question:
Added pre tags

Hi,
I read your code. Your mistake is in this line:
C#
string date = getReadDate.ToString();

You need to write this in order to fetch a DateTime value from the database:
C#
DateTime date = getReadDate.GetDateTime(0);


The point is that every data type has a specific method in SqlDataReader. Take a look at this class here:
http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqldatareader.aspx[^]

I hope it helps,
Cheers.
 
Share this answer
 
v4
Instead of using ExecuteReader() using ExecuteScalar(). It returns the first value from the first row as an Object.

C#
Object temp = readDate.ExecuteScalar();


Also, you may have to alias the column in your SQL so that it has a name.

SQL
Select max(RecordDate) AS MaxDate from OEETable
 
Share this answer
 
Thanks Ryan, but Execute Scalar wont do it for me as the first column in my table is RecordID and i can retrieve that just fine as it is just an integer, the RecordDate column is the second column in my table.
 
Share this answer
 
Comments
André Kraak 5-Apr-12 16:25pm    
If you have a question about or comment on a given solution use the "Have a Question or Comment?" option beneath the solution. When using this option the person who gave the solution gets an e-mail message and knows you placed a comment and can respond if he/she wants.

Please move the content of this solution to the solution you are commenting on and remove the solution.
Thank you.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900