我创建了一个简单的asp.net表单,允许用户查看培训的日期列表并注册该日期,他们手动输入他们的名字和employeeid(我不想让dulpicate的员工ID),所以我需要弄清楚如何在c#..上检查这个。
代码:
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();
答案 0 :(得分:3)
这样,只有在不存在的情况下,您的查询才会插入数据
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) ";