SqlCommand read one value

后端 未结 2 1237
情书的邮戳
情书的邮戳 2020-12-21 15:21

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

string sqlSelect = \"Select TOP 1 Quotation.SentToSupp as SentToSupp         


        
相关标签:
2条回答
  • 2020-12-21 16:10

    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

    0 讨论(0)
  • 2020-12-21 16:23

    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.

    0 讨论(0)
提交回复
热议问题