Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the return value of Database.ExecuteSqlCommand?

Modifying an answer from this question slightly, suppose I run this code:

public int SaveOrUpdate(MyEntity entity)
{
    var sql =  @"MERGE INTO MyEntity
                USING 
                (
                   SELECT   @id as Id
                            @myField AS MyField
                ) AS entity
                ON  MyEntity.Id = entity.Id
                WHEN MATCHED THEN
                    UPDATE 
                    SET     Id = @id
                            MyField = @myField
                WHEN NOT MATCHED THEN
                    INSERT (Id, MyField)
                    VALUES (@Id, @myField);"

    object[] parameters = {
        new SqlParameter("@id", entity.Id),
        new SqlParameter("@myField", entity.myField)
    };
    return context.Database.ExecuteSqlCommand(sql, parameters);
}

This will actually run and it returns an int. What does the int mean? The documentation just says

The result returned by the database after executing the command.

I did a couple tests and it looks like it's 1 if it modified a row, and 0 if nothing changed. Is the return value the number of rows modified?

like image 895
Matthew Avatar asked Feb 23 '26 04:02

Matthew


1 Answers

For most databases, that means the number of rows affected by the command. I theory though, god forbid that such a thing exists, the database vendor is free to return whatever and you would then need to look in the documentation for the particular database for what the number means.

like image 196
Pauli Østerø Avatar answered Feb 25 '26 18:02

Pauli Østerø



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!