Tuesday, July 30, 2013

Output Parameters in C# with Sql Server 2008 Procedure

Scenario is when you want to change the old password with new password. You pass these credentials to sql procedure "usp_changePassword".


C#
                cmd = new SqlCommand(_procChangeUserPassword, _con);
                cmd.CommandType = CommandType.StoredProcedure;
                cmd.Parameters.AddWithValue("@Userid", userid);
                cmd.Parameters.AddWithValue("@oldpassword", oldpassword);
                cmd.Parameters.AddWithValue("@newpassword", newpassword);
                cmd.Parameters.AddWithValue("@status", SqlDbType.Bit).Direction = ParameterDirection.Output;
                cmd.ExecuteNonQuery();
                bool status = Convert.ToBoolean(cmd.Parameters["@status"].Value);

                return status;
Details:

  • _con is the connectstring after connection
  • userid is the id of the user
  • old password and new password
  • Status field which will carry the bool value whether the operation was successful or not.


Sql Server Procedure: usp_changepassword

Create procedure usp_changePassword
@Userid bigint,
@oldpassword nvarchar(200),
@newpassword nvarchar(200),
@status bit output
as
begin

if exists(SELECT * FROM GH_MemberShip_User where id=@Userid)
begin
if exists(select * from userpass where Password=@oldpassword)
begin
update userpadd set Password=@newpassword, ModifiedDate=GETUTCDATE() where UserID=@Userid
set @status=1
end
else
set @status=0
end
else
set @status=0

select @status
end

Details:
 Now how to test this procedure in sql server:
           declare @status bit
           exec GH_sp_ChangePassword 4,'arjun456','arjun123',@status output
           select @status

Well i hope the code to use the output parameter in c# and sql server will help you in some way.