I am currently working with C#, SQL Server and writing a Web API application.
I am creating SQL Server stored procedures and have several working, including inserting into the database, along with updating entries in the database. However, I am now trying to work with outputs, and am struggling with something simple.
I am looking to pass in an email address, and return the row id for the first match.
Here is the stored procedure:
CREATE PROCEDURE USER_PROCEDURE_GET_ID
@Email VARCHAR(200),
@id int Out
AS
SELECT *
FROM [dbo].[Users]
WHERE Email = @Email
SET @id = id
RETURN @id
Here is the C# code
public int GetID( string emailAddress )
{
// Create an SQL command
SqlCommand command = new SqlCommand();
command.Connection = this.sqlConnection;
// Set the command type to use a stored procedure
command.CommandType = CommandType.StoredProcedure;
// The name of the stored procedure
command.CommandText = "USER_PROCEDURE_GET_ID";
// Add the email address
command.Parameters.Add( new SqlParameter( "@email", emailAddress ) );
// Add the output param
SqlParameter outputParam = new SqlParameter( "@id", SqlDbType.Int )
{
Direction = ParameterDirection.Output
};
command.Parameters.Add( outputParam );
// Create the reader
SqlDataReader reader = null;
// Execute the command
try
{
reader = command.ExecuteReader();
}
catch (InvalidCastException ex)
{
}
catch (SqlException ex)
{
}
catch (InvalidOperationException ex)
{
}
catch (IOException ex)
{
}
finally
{
reader.Close();
}
Debug.Write( "user id: " + outputParam.Value.ToString() );
return 0;
}
I am aware that i am am not handling exceptions properly and that I'm not doing anything with the value returned. At this point I don't get a value returned and also get an error:
System.NullReferenceException: Object reference not set to an instance of an object.
Thanks in advance.