我怎样才能获取存储过程的返回值在C#中? [英] How can I get Stored Procedure return value in C#?
问题描述
我有一个存储过程,做一些操作,返回1或0,如下
CREATE PROCEDURE dbo.UserCheckUsername11
(
@用户名为nvarchar(50)
)
如
开始
SET NOCOUNT ON;
是否存在(选择用户名与用户其中username = @用户名)
返回1
其他
返回0
结束
和在C#我想要得到这个返回的值我尝试 ExcuteScalar
但它没有返回任何值(我知道如果我把返回0
与选择0
ExcuteScalar
将catach ..但它是什么办法,让我得到返回的值替换返回
与选择
?
注:我不希望用户存储过程的输出参数也
在本质上,你必须定义为方向的返回值的参数。
您可以在这里找到一些例子:使用ADO .NET与SQL Server 在这里:的从SQL存储过程得到返回值。
下面谈到的有关部分从第一个链接引用:
要获得一个价值回归 声明中,你需要做的 以下内容:
//添加一个新的参数,以任何名义,我们希望 - 它为我们自己
只有//用
的SqlParameter sqlParam = com.Parameters.Add(@返回值,SqlDbType.Int);
//设置方向标志,这样它会充满的返回值
myParm.Direction = ParameterDirection.ReturnValue;
然后,在存储过程有 被执行,
INT的returnValue =(int)的com.Parameters [@返回值。值
将检索所设定的值。
I have a stored Procedure that do some operation and return 1 or 0 as below
CREATE PROCEDURE dbo.UserCheckUsername11
(
@Username nvarchar(50)
)
AS
BEGIN
SET NOCOUNT ON;
IF Exists(SELECT UserID FROM User WHERE username =@Username)
return 1
ELSE
return 0
END
and in C# i want to get this returned value i try ExcuteScalar
but it didn't return any value ( i know if i replace return 0
with Select 0
ExcuteScalar
will catach it .. but is it any way that allow me to get returned value with replace return
with select
?
NOTE : I don't want to user stored procedure output parameter also
In essence you have to define a parameter with "direction" return value.
You can find some examples here: Using ADO.NET with SQL Server and here: Get the Return Value from an SQL Stored Procedure.
Here comes the relevant part from the first link cited:
To get the value of a RETURN statement, you need to do the following:
// add a new parameter, with any name we want - its for our own
// use only
SqlParameter sqlParam = com.Parameters.Add("@ReturnValue", SqlDbType.Int);
// set the direction flag so that it will be filled with the return value
myParm.Direction = ParameterDirection.ReturnValue;
Then, after the stored procedure has been executed,
int returnValue = (int)com.Parameters["@ReturnValue"].Value
will retrieve the value that was set.
这篇关于我怎样才能获取存储过程的返回值在C#中?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!