简体   繁体   中英

ExecuteNonQuery() returns -1 from Oracle Procedure

I have the following part of code in my .net C# console app

var SGCodProdInsert = new OracleCommand
                        {
                            Connection = con,
                            CommandText = ProductFirstInsert,                                
                            CommandTimeout = 15,
                            Transaction = dbContextTransaction
                        };
                        var t = SGCodProdInsert.ExecuteNonQuery();

The Oracle command( ProductFirstInsert ) that i pass is like this:

BEGIN
INSERT INTO Products_TEST (ProductName,ProductCode) VALUES ('TEST','TEST');
INSERT INTO Products_TEST (ProductName,ProductCode) VALUES ('TEST1','TEST1');
INSERT INTO Products_TEST (ProductName,ProductCode) VALUES ('TEST2','TEST2');

.

.

.

 INSERT INTO Products_TEST (ProductName,ProductCode) VALUES ('TESTn','TESTn');
 END;

As a result in t i get -1 and i can understand why...So my question is the following: How can I take in single integer how many records have inserted in my table from an oracle procedure ?

The simplest way is to execute a count(*) command before and after your command:

var SGCodProdInsert = new OracleCommand
{
    Connection = con,
    CommandText = ProductFirstInsert,
    CommandTimeout = 15,
    Transaction = dbContextTransaction
};
var CountTable = new OracleCommand
{
    Connection = con,
    CommandText = "select count(*) from Products_TEST",
    CommandTimeout = 15,
    Transaction = dbContextTransaction
};
decimal beforeInsert = Convert.ToDecimal(CountTable.ExecuteScalar());
SGCodProdInsert.ExecuteNonQuery();
decimal afterInsert = Convert.ToDecimal(CountTable.ExecuteScalar());

Console.WriteLine($"Inserted rows: {afterInsert - beforeInsert}");

Otherwise you would have to create a temporary Oracle function and read SQL%ROWCOUNT

For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. For all other types of statements, the return value is -1.

The own Doc from Microsoft is saying this.

Ref: https://docs.microsoft.com/en-us/dotnet/api/system.data.sqlclient.sqlcommand.executenonquery?view=dotnet-plat-ext-3.1

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM