My application allows the user to add a new player to the database. Before adding a new player, I'd like for a stored procedure to check whether or not a player with the first name and last name exists. I want the stored procedure to return a bit value, 0 or 1. My C# method will then return this value and the program can decide whether or not to proceed with the creation.
Note that I've cut some of the general validation out of the code below, i.e. if the fields are empty, or the balance TextBox is invalid etc..
I'm also aware that I may be using the wrong datatype when handling the returned value. i.e. int instead of bool.
When I run this, I get an error saying that my SP requires an input parameter @ReturnedValue.
Cheers
Player newPlayer = new Player();
newPlayer.PlayerID = Guid.NewGuid();
newPlayer.FirstName = TextBoxFirstName.Text;
newPlayer.LastName = TextBoxLastName.Text;
newPlayer.Balance = Convert.ToDouble(TextBoxInitialCredit.Text);
var exists = newPlayer.CheckExists();
if (exists == 1)
{
newPlayer.AddPlayer();
}
and here's the method:
public int CheckExists()
{
SqlConnection myConnection = new SqlConnection(ConfigurationManager.ConnectionStrings["Badminton"].ConnectionString);
myConnection.Open();
SqlCommand SqlCmd = new SqlCommand("CheckPlayerExists", myConnection);
SqlCmd.CommandType = CommandType.StoredProcedure;
SqlCmd.Parameters.Add("@FirstName", SqlDbType.NVarChar, 50).Value = FirstName;
SqlCmd.Parameters.Add("@LastName", SqlDbType.NVarChar, 50).Value = LastName;
SqlCmd.Parameters.Add("@ReturnValue", SqlDbType.Int, 2).Direction = ParameterDirection.Output;
SqlDataAdapter myDataAdapter = new SqlDataAdapter(SqlCmd);
DataSet myDataSet = new DataSet();
myDataAdapter.Fill(myDataSet);
int exists = Convert.ToInt32(SqlCmd.Parameters["@ReturnValue"].Value);
myConnection.Close();
return exists;
}
and now my stored procedure:
CREATE PROCEDURE dbo.CheckPlayerExists
@firstName nvarchar(50),
@lastName nvarchar(50),
@ReturnValue bit output
AS
BEGIN
IF EXISTS (SELECT * FROM Players WHERE FirstName = @firstName AND LastName = @lastName)
SET @ReturnValue = 1
ELSE
SET @ReturnValue = 0
RETURN @ReturnValue
END
FirstName = @firstName OR LastName = @lastName