Does ExecuteScalar return immediately after SELECT?

Interesting behavior was noticed by me recently.

When the MS SQL stored procedure was started using SqlCommand.ExecuteScalar (), my application does not seem to be completely aware of any SQL errors or PRINT that appear after performing SELECT.

The most likely explanation is that flow control is transferred to C # immediately after the appearance of any SELECT result, without waiting for the stored procedure to complete (although the stored procedure continues to execute silently under it).

The obvious advantage is increased performance (no need to wait, as the result is already known), unfortunately, the C # application is not aware of any SQL exceptions that may occur after this point.

Can anyone confirm my explanation? Can this behavior be changed?

+5
source share
1 answer

The ExecuteNonQuery method will call "ExecuteReader" and immediately call "Close" on the returned reader object. ExecuteScalar will call Read once, select the first value (index 0), and then call Close.

Since the DataReader is essentially nothing more than a specialized network stream, any information that is returned even at the current location (when Close is called) can never reach the real client components, even if the server could send it. Implementation as such avoids the return of a huge amount of data when not necessary.

.

  • , ExecuteReader, :

    using(var reader = command.ExecuteReader())
    {
        do 
        {
              while (reader.Read()) { /* whatever */ };
        } while (reader.NextResult());
    }
    
  • , " " . :

    create proc Demo
    as
    declare @result int
    select top 1 @result = Id from MyTable where Name = 'testing'
    print 'selected result...'
    select @result Id  -- will send a column called "Id" with the previous value
    go
    
+1

All Articles