關於ExecuteNonQuery執行的返回值(SQL語句、存儲過程)

由於msdn中說返回受影響的行數:sql

Executes a Transact-SQL statement against the connection and returns the number of rows affected.數據庫

可是卻沒看到備註裏說函數

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.spa

對於UPDATE, INSERT,和 DELETE返回受影響的函數,可是對於全部其餘類型的語句,返回值爲 -1。若是發生回滾,返回值也爲 -1。.net

用到過ExecuteNonQuery()函數的朋友們在開發的時候確定這麼用過.code

if(cmd.ExecuteNonQuery("xxxx")>0)orm

{ip

     //執行成功!ci

}開發

else

{

     //執行失敗!

}

經過ExecuteNonQuery()的返回值來判斷操做數據庫的成功與否是能夠的.可是要分狀況.

1.ExecuteNonQuery() 不執行存儲過程.

此時若是對數據庫執行,插入,更新,刪除操做,返回的是 受影響的行數.(及一個大於等於0的整數)

2.ExecuteNonQuery() 執行查詢不返回影響的行數.

2.ExecuteNonQuery   執行存儲過程.

[1].存儲過程有返回值(傳出參數)

    (1).把數據庫中受影響的行數賦給返回值,這是獲得的返回值是受影響的函數(大於或等於0的整數).

    (2).把某個值賦給返回值.

[2].存儲過程沒有返回值

    執行成功後返回 -1.

(沒有返回值的存儲過程理應 返回 受影響的行數 (執行 增刪改) 可是.但咱們在ado.net中執行存儲過程的時候,dotnet 自動爲給了存儲過程一個默認值:set nocount on;

因此給咱們的感受是執行存儲過程默認返回 -1  )

ExecuteNonQuery 返回的是最後一條SQL語句影響的行數。
若是你想獲得存儲過程當中的Return,那存儲過程當中,你必須寫Return 0或Return 1。  Return 只能是int
另外還有輸出參數,能夠是任意類型。
概念別搞混了。

假設有存儲過程以下:

SQL code
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
CREATE  PROCEDURE  [dbo].[sp_add]
(
     @x  int ,
     @y  int ,
     @r  int  output
)
AS
BEGIN
     SET  NOCOUNT  ON ;
 
     set  @r =  @x + @y;
     
     return  0;
END



調用方式:

C# code
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
using  (SqlConnection conn =  new  SqlConnection())
{
                 conn.ConnectionString = xxxx;
                 conn.Open();
                 using  (SqlCommand cmd = conn.CreateCommand())
                 {
                     cmd.CommandType = CommandType.StoredProcedure;
                     cmd.CommandText =  "sp_add" ;
                     SqlParameter[] ps =  new  SqlParameter[4];
                     ps[0] =  new  SqlParameter( "@x" , 1);
                     ps[1] =  new  SqlParameter( "@y" , 2);
                     ps[2] =  new  SqlParameter( "@r" , SqlDbType.Int);
                     ps[2].Direction = ParameterDirection.Output;
                     ps[3] =  new  SqlParameter();
                     ps[3].SqlDbType = SqlDbType.Int;
                     ps[3].Direction = ParameterDirection.ReturnValue;
                     cmd.Parameters.AddRange(ps);
                     int  r = cmd.ExecuteNonQuery();
 
                     Console.WriteLine( string .Format( "@r={0},存儲過程返回:{1},ExecuteNonQuery返回:{2}" , ps[2].Value, ps[3].Value, r));
                 }
  }
相關文章
相關標籤/搜索