I'm getting an intermittent null value for an output parameter for a stored procedure I have. I'm wondering if it has to do with the NOLOCK inside the stored procedure. It works most of the time, it's intermittently failing. Especially under high load. Most of the time it returns the "y" or "n" you would expect.
SqlConnection con = getCon();
SqlCommand cmd = new SqlCommand("loginRecord", con);
cmd.CommandType = CommandType.StoredProcedure;
cmd.Parameters.Add(new SqlParameter("@username", username));
cmd.Parameters.Add(new System.Data.SqlClient.SqlParameter("@exists", System.Data.SqlDbType.VarChar, 3, System.Data.ParameterDirection.Output, false, ((System.Byte)(0)), ((System.Byte)(0)), "", System.Data.DataRowVersion.Current, null));
try
{
con.Open();
cmd.ExecuteNonQuery();
}
catch (Exception ex)
{
Util.sendErrorEmail(ex.ToString());
}
finally
{
con.Close();
}
//The following line is the one that throws an "Object reference not set to an instance of an bject." exception
string userExists = cmd.Parameters["@exists"].Value.ToString();
Here is the stored procedure:
ALTER PROCEDURE [dbo].[loginRecord]
(
@username nvarchar(100),
@exists char(1) OUTPUT
)
AS
IF EXISTS(select username from Users WITH (NOLOCK) where username = @username)
BEGIN
set @exists='y'
END
ELSE
BEGIN
set @exists='n'
--insert user account--
insert into Users (username, datejoined)
values (@username, getdate())
END
insert into Logins (username, logged)
values (@username, getdate())
GO