Click here to Skip to main content
15,884,473 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have the following stored procedure:
C#
SET XACT_ABORT ON

BEGIN TRAN

INSERT INTO SystemUsers (usr_us_id)
     SELECT us_pk
       FROM SFSUsers LEFT OUTER JOIN SystemUsers ON us_pk = usr_us_id
      WHERE usr_us_id IS NULL

INSERT INTO Addresses (add_usr_id)
     SELECT usr_id
       FROM SystemUsers LEFT OUTER JOIN Addresses ON usr_id = add_usr_id
      WHERE add_usr_id IS NULL

COMMIT TRAN


END

Being called from a business object which has an ExecuteScalar() method defined in the parent class ...
C#
public int SynchronizeWithSecurity()
{
    sqlCommandBuilderApp oSQLCmd = new sqlCommandBuilderApp("SystemUsers_SynchronizeWithSecurity",CommandType.Text);

    int numberSynched = Convert.ToInt32(ExecuteScalar(oSQLCmd.SqlCmd));

    return (int)numberSynched;
}

Even though three user records were synchronized ... ExecuteScalar always returns 0. I even tried to use SELECT @@ROWCOUNT at the end of the proc. but no dice. Does the Transaction processing block the number of affected rows from being returned to the invoking method?

Thanks
Posted
Comments
ZurdoDev 31-Mar-14 16:41pm    
ExecuteScalar will return the first column of the first record so to get a record count you definitely will have to return it from the stored proc. You likely need to store the row count into a variable between your insert statement and the commit tran. Then return that value.

1 solution

Have a look here: SqlCommand.ExecuteScalar Method [^] plus @@ROWCOUNT[^]

If you would like to return the count affected records, you need to write SP in that way:

SQL
DECLARE @inserted INT
SET @inserted = 0

INSERT ....
SET @inserted = @@ROWCOUNT


INSERT ...
SET @inserted = @inserted + @@ROWCOUNT 

SELECT @inserted AS ReturnedValue
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month


CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900