如何从存储过程返回GUID / ID

时间:2017-02-21 23:23:45

标签: c# asp.net sql-server stored-procedures

我有一个存储过程。它应该返回GUID / ID,但在执行它之后返回值2或-1。我希望它只返回GUID / ID。请帮我解决这个问题。

这是代码

存储过程:

create procedure SampleAddUser1
    (@Name nvarchar(MAX),
     @MailID nvarchar(MAX),
     @MobileNumber varchar(12),
     @Password nvarchar(MAX),
     @OTPNo varchar(10),
     @OTPExp datetime,
     @UserID uniqueidentifier output)
as
    if (not exists (select * from tbl_UserDetails where MobileNumber=@MobileNumber))
    begin
        begin transaction
            set @UserID = NEWID()

            insert into tbl_UserDetails(UserID, Name, Password, MobileNumber, MailID)
            values (@UserID, @Name, @Password, @MobileNumber, @MailID)

            insert into tbl_OTPDetails(UserId, OTPNo, OTPExp)
            values (@UserID, @OTPNo, @OTPExp)

            commit transaction
end

C#代码在这里.....

SqlParameter sqlParam = new SqlParameter("@UserID", SqlDbType.UniqueIdentifier);
sqlParam.Direction = ParameterDirection.Output;
param[6] = sqlParam;

r = _obj.ExecuteNonquery("SampleAddUser1", CommandType.StoredProcedure, param.ToArray());

Obj.ExecuteNonQuery

   public int ExecuteNonquery(string commandText, 
   CommandType commandType, SqlParameter[] parameters)
    {
        try
        {
            cmd = new SqlCommand(commandText,con);
            cmd.CommandType = commandType;

            foreach (SqlParameter p in parameters)
            {
                if (p.Value == null)
                {
                }
                cmd.Parameters.Add(p);
            }
            int output= cmd.ExecuteNonQuery();
            con.Close();
            return output;
        }
        catch (Exception ex)
        {
            throw new ArgumentException(ex.Message);
        }
        finally
        {
            con.Close();
        }
    }

2 个答案:

答案 0 :(得分:3)

获取输出参数的.Value属性应该非常简单:

SqlParameter sqlParam = new SqlParameter("@UserID", SqlDbType.UniqueIdentifier);
sqlParam.Direction = ParameterDirection.Output;
param[6] = sqlParam;
r = _obj.ExecuteNonquery("SampleAddUser1", CommandType.StoredProcedure, param.ToArray());

// get the returned parameter
Guid? userId = sqlParam.Value as Guid?;

我注意到存储过程的一件事是不保证生成NEWID()(在数据库中已经存在具有相同@MobileNumber的记录的情况下)。在这种情况下,最好是安全的,并使用Guid?作为返回类型。

答案 1 :(得分:2)

您无法从ExecuteNonQuery()的返回值中获取返回值或输出参数。这只会返回受影响的行。

获取输出参数的值:

var conn = new SqlConnection("my connection string");
var cmd = conn.CreateCommand();
cmd.CommandText = "dbo.MyProc";
cmd.CommandType = CommandType.StoredProcedure;

var sqlParam = new SqlParameter("@UserID",
SqlDbType.UniqueIdentifier);
sqlParam.Direction = ParameterDirection.Output; 

cmd.Parameters.Add(sqlParam);
cmd.ExecuteNonQuery();
// you can now access your output param
return (Guid)sqlParam.Value;