SqlCommand read one value

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.

  • Get list of tables but not include system tables (SQL Server 2K)?
  • SqlServer to Postgres DDL migration/conversion
  • How to select row with max value when duplicate rows exist in SQL Server
  • SELECT query with multiple sub-queries for counts
  • Using ZF2, create a WITH statement?
  • Problem using SQL Agent to run SSIS Packages - fails with “DTSER_FAILURE(1)”
  • But I don’t know how to get my DateTime value… Must to use something like ExecuteReader?

    Thank you in advance!!

  • Error - “The server was not found or was not accessible” when trying to connect to sql server database
  • Connecting to sql server database mdf file without installing sql server on client machine?
  • Selecting chinese characters in SQL server 2008
  • SQL string comparison, greater than and less than operators
  • Getting lowest level in a tree from any higher level with a self-join
  • Force multithreading in select query?
  • 2 Solutions collect form web for “SqlCommand read one value”

    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.

    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 if, for some reason, there is no record in the result returned

    MS SQL Server is a Microsoft SQL Database product, include sql server standard, sql server management studio, sql server express and so on.