2

我从如下存储过程中返回 0 和 1。如何在 c# asp.net 文件中获取它?

ALTER procedure [dbo].[crudprocedure] 

    @getusername        varchar(20),
    @getfirstname       varchar(20),
    @getlastname        varchar(20),
    @getaddress         varchar(20)
 as 
 begin
IF not exists (select username from crudtable where username=@getusername)
begin 
insert into crudtable(username,firstname,lastname,address) 
values (@getusername,@getfirstname,@getlastname,@getaddress)
return 0
end
else
return 1
end
4

1 回答 1

1

如果您使用的是 SQL Server - 请在此处尝试此代码:

using (SqlConnection conn = new SqlConnection("...put your connection string here..."))
using (SqlCommand cmd = new SqlCommand("dbo.crudprocedure", conn))
{
   cmd.CommandType = CommandType.StoredProcedure;

   cmd.Parameters.Add("@getusername", SqlDbType.VarChar, 20).Value = "test";
   cmd.Parameters.Add("@getfirstname", SqlDbType.VarChar, 20).Value = "test";
   cmd.Parameters.Add("@getlastname", SqlDbType.VarChar, 20).Value = "test";
   cmd.Parameters.Add("@getaddress", SqlDbType.VarChar, 20).Value = "test";

   // define additional paramter of Direction = ReturnValue
   cmd.Parameters.Add("RETURN_VALUE", SqlDbType.Int).Direction = ParameterDirection.ReturnValue;

   // open connection, execute stored proc, close connection
   conn.Open();
   cmd.ExecuteNonQuery();
   conn.Close();

   // fetch the value of the "ReturnValue" parameter
   int returnValueInt = Convert.ToInt32(cmd.Parameters["RETURN_VALUE"].Value);
}

基本上,由于您使用RETURN 1存储过程发回该值,因此您需要向SqlCommand具有.Directionof的对象添加一个附加参数ParameterDirection.ReturnValue

该参数将设置为您使用从存储过程发回的值RETURN ....

于 2012-07-26T13:32:49.517 回答