由于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
另外还有输出参数,能够是任意类型。
概念别搞混了。
假设有存储过程以下:
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
|
调用方式:
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));
}
}
|