0

I created a simple asp.net form which allow users to view a list of dates for a training and register for that date , they enter their name and employeeid manually ( i dont want to allow dulpicate employe ids), so I need to figure out how to check this on c#..

code:

 public string GetConnectionString()
    {
        //sets the connection string from your web config file "ConnString" is the name of your Connection String
        return System.Configuration.ConfigurationManager.ConnectionStrings["MyConnectionString"].ConnectionString;


    }

    private void checkContraint()
    {

        SqlConnection conn = new SqlConnection(GetConnectionString());
        string sql = "Select "; //NEED HELP HERE

    }


    private void InsertInfo()
    {
        var dateSelected = dpDate.SelectedItem.Value;
        SqlConnection conn = new SqlConnection(GetConnectionString());

        string sql = "INSERT INTO personTraining (name,department,title,employeeid,training_id, training,trainingDate,trainingHour, trainingSession)SELECT @Val1b+','+@Val1,@Val2,@Val3,@Val4,training_id,training,trainingDate,trainingHour,trainingSession FROM tbl_training WHERE  training_id =@training_id ";


        try
        {
            conn.Open();
            SqlCommand cmd = new SqlCommand(sql, conn);


            cmd.Parameters.AddWithValue("@Val1", txtName.Text);
            cmd.Parameters.AddWithValue("@Val1b", txtLname.Text);
            cmd.Parameters.AddWithValue("@Val2", txtDept.Text);
            cmd.Parameters.AddWithValue("@Val3", txtTitle.Text);
            cmd.Parameters.AddWithValue("@Val4", txtEmployeeID.Text);

            //Parameter to pass for the select statement
            cmd.Parameters.AddWithValue("@training_id", dateSelected);
            cmd.CommandType = CommandType.Text;
            //cmd.ExecuteNonQuery();

            int rowsAffected = cmd.ExecuteNonQuery();
            if (rowsAffected == 1)
            {

                //Success notification            // Sends user to redirect page

                Response.Redirect(Button1.CommandArgument.ToString());
                ClearForm();
            }
            else
            {
                //Error notification      

            }  
        }
        catch (System.Data.SqlClient.SqlException ex)
        {
            string msg = "Insert Error:";
            msg += ex.Message;
            throw new Exception(msg);

        }
        finally
        {
            conn.Close();
        }
    } 

    protected void Button1_Click(object sender, EventArgs e)
    {

        checkContraint();
        InsertInfo();
5
  • Did you need to limit it to one traininf session per employee ID? Or one per date, one per session, etc? Commented Nov 14, 2011 at 21:34
  • Just limit one employee id (unique) in entire table Commented Nov 14, 2011 at 21:44
  • Looks like Royi's answer does that. While not a separate validation query for your check constraint method, it should hit your error notification handler in InsertInfo. Commented Nov 14, 2011 at 21:47
  • 1
    Why don't you put a unique constraint in your database. This will cause an exception if they try to insert data in a way not desired. You can then catch the sql exception in your application that you can handle gracefully. Commented Nov 14, 2011 at 21:53
  • HOw do I add this constraint in sql server management studio 2008? Commented Nov 14, 2011 at 22:06

1 Answer 1

3

this way , your query will insert data only if not exists already

 string sql = "INSERT INTO personTraining (name,department,title,employeeid,training_id, training,trainingDate,trainingHour, trainingSession)SELECT @Val1b+','+@Val1,@Val2,@Val3,@Val4,training_id,training,trainingDate,trainingHour,trainingSession FROM tbl_training WHERE  training_id =@training_id and not exists (select 1 from personTraining pp where pp .employeeid=@Val4) ";
Sign up to request clarification or add additional context in comments.

6 Comments

I have never seen select 1 from personTraining pp where pp .employeeid=@Val4.... what does it do?
insert this :'xxxxx' to table 'vvvvvvvv' but only if 'ccccc' and there isnt already a record for the specified employee id
it can be 2,3,4, it doesnt matter : "select something"
do you mean SELECT TOP 1 and shouldnt you be selecting an id to check it is not in?
It will return a literal value of 1 if the row exists. Nothing more. Optimal if the table is indexed on the employee ID as the query will be satisfied by the index alone. Could return employeeid and not touch the table data as well. But the result doesn't matter, only the existence of one or more rows in the subquery's result set.
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.