3

I have a problem with the value returned from SqlCommand, I have this code:

string sqlSelect = "Select TOP 1 Quotation.SentToSupp as SentToSupp FROM Quotation JOIN Notifications ON Quotation.QuotationId = QuotationID ";

SqlCommand Comm = new SqlCommand(sqlSelect, this.Connection);

sqlSelect query selects the first DateTime value. When I call to SqlCommand I want to get this value (just one value). I add the query and my connection fine.

But I don't know how to get my DateTime value... Must to use something like ExecuteReader?

Thank you in advance!!

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459
userS
  • 35
  • 1
  • 1
  • 3
  • 1
    Take a look @ `ExecuteScalar` ; http://msdn.microsoft.com/en-us/library/system.data.sqlclient.sqlcommand.executescalar.aspx – Alex K. Apr 05 '13 at 11:01

2 Answers2

9

ExecuteReader works but more objects and more code are required - (An SqlDataReader, call to Read and Extract value). Instead you could simply use the ExecuteScalar method of the SqlCommand object (It returns just the first column of the first row of the resultset)

string sqlSelect = "Select TOP 1 Quotation.SentToSupp as SentToSupp FROM ....";
SqlCommand Comm = new SqlCommand(sqlSelect, this.Connection);
object result = Comm.ExecuteScalar();
if(result != null)
   DateTime dtResult = Convert.ToDateTime(result);

Just pay attention to the fact that ExecuteScalar could return a null value. For example, if there is a WHERE condition that excludes every row from the result returned.

Steve
  • 213,761
  • 22
  • 232
  • 286
3

Use SqlCommand.ExecuteScalar method - Executes the query, and returns the first column of the first row in the result set returned by the query. Additional columns or rows are ignored.

Alex
  • 8,827
  • 3
  • 42
  • 58