Click here to Skip to main content
14,176,607 members
Rate this:
 
Please Sign up or sign in to vote.
See more:
Hello,

I want to delete all the rows of a table so i use the following code in my project:-
public int DeleteALL()
      {

          SqlCommand cmd = new SqlCommand(cn);
          cmd.CommandText="Truncate Table TempMonth";
              

          int i = -1;
          try
          {
              i = cmd.ExecuteNonQuery();

          }

          catch (Exception ex)
          {
              this.error = ex.Message;

          }
          return i;
      } 


now my prob is.... all the rows from the table is deleted but the value of i is still -1. That means ExecuteNonQuery() doesn't return anything. what is the prob here anyone please give answer.
Posted
Updated 30-Aug-11 23:53pm
v2
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 1

The query will return -1 rather than a count.

As per msdn documentation[^],
"For UPDATE, INSERT, and DELETE statements, the return value is the number of rows affected by the command. When a trigger exists on a table being inserted or updated, the return value includes the number of rows affected by both the insert or update operation and the number of rows affected by the trigger or triggers. For all other types of statements, the return value is -1. If a rollback occurs, the return value is also -1."
   
v3
Comments
Uday P.Singh 31-Aug-11 6:05am
   
exactly my 5!
Abhinav S 31-Aug-11 6:06am
   
Thanks.
Anil Honey 206 31-Aug-11 6:18am
   
its Correct.
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 2

AFAIK: For UPDATE, INSERT, and DELETE statements, ExecuteNonQuery() returns the number of rows affected by the command.

For all other types of statements, the return value is -1.

And here you are using truncate not UPDATE, INSERT, and DELETE.

hope it helps :)
   
Comments
Abhinav S 31-Aug-11 6:04am
   
Same answer as me. My 5.
Uday P.Singh 31-Aug-11 6:13am
   
yeah Abhinav , it's a great coincidence and thanks for 5
Rate this: bad
 
good
Please Sign up or sign in to vote.

Solution 3

No, you are slightly confused. TRUNCATE TABLE does not have a return value, so the ExecuteNonQuery returns -1.
If you set your initial value of i to 1234 instead of -1, you will see what I mean.
   

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


Advertise | Privacy | Cookies | Terms of Service
Web02 | 2.8.190525.1 | Last Updated 31 Aug 2011
Copyright © CodeProject, 1999-2019
All Rights Reserved.
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100