3

I would like to execute multiple select, insert, update statements in one batch, using one SqlCommand, for improved performance.
The CommandText is assembled dynamically from multiple predefined insert, update statements (SqlParams are assembled dynamically, too). The inserts sometimes works on tables with autoid fields, so getting back the last inserted id is necessary. I use 'SELECT SCOPE_IDENTITY()' for that. A typically assembled CommandText looks like this:

INSERT xxxxx ;
SELECT SCOPE_IDENTITY();
INSERT yyyyy ;
SELECT SCOPE_IDENTITY();
INSERT zzzzz ;
UPDATE xxxxx ;
INSERT wwwww ;
SELECT SCOPE_IDENTITY();

I would like to retreive all the scope_identity values, as well as the number of affected rows. ExecuteNonQuery and ExecuteScalar is not usable, because they give back only single values. ExecuteReader is better, it gives back information from the selects, (gives 3 results in the example above), but I needs the affected rows as well (for checking the execution).

    public IList Execute()
    {
        var results = new ArrayList();

        using (var command = connection.CreateCommand())
        {
            command.Transaction = transaction;

            var commandText = new StringBuilder();
            .... building commandtext dynamically
            command.CommandText = commandText.ToString();

            command.Parameters.AddRange(... adding paramters dynamically);

            var reader = command.ExecuteReader();
            do
            {
                if (reader.Read())
                    results.Add(reader.IsDBNull(0) ? null : reader.GetValue(0));
            } while (reader.NextResult());
            reader.Close();
        }
        return results;
    }

Any ideas how to get it?

Mike Perrenoud
  • 66,820
  • 29
  • 157
  • 232
Ligu
  • 31
  • 2
  • @@ROWCOUNT is your friend. Check here: http://stackoverflow.com/questions/1103260/return-number-of-rows-affected-by-update-statements – Jon Raynor Aug 30 '13 at 19:31

1 Answers1

2

You can add as a very first line to the string with your SQL Statements:

"DECLARE @rCount int; SET @rCount = 0;"

Then after every action (INSERT/UPDATE) do:

"SET @rCount = @rCount + @@ROWCOUNT"

and add as a very last command

"SELECT @rCount"
Yuriy Galanter
  • 38,833
  • 15
  • 69
  • 136