Edit or Add database

Hello,
I want to insert two fields into or update database accordingly. It depends, if there are not such ones existing in the database, then insert them. If they are already there, it may be updated.

The two fields come from two text boxs.
I only finish insert part, can we put them together?
 protected void Add_Click(object sender, EventArgs e)
        {
            SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["MembershipDB"].ConnectionString);
            con.Open();
            SqlCommand cmd = new SqlCommand();
            cmd.Connection = con;
            
            cmd.CommandText = "Insert MedOrganization(OrgCode, OrgName) values(@OrgCode,@OrgName)";
            cmd.Parameters.Add("OrgCode", SqlDbType.VarChar).Value = TextBox1.Text;
            cmd.Parameters.Add("OrgName", SqlDbType.VarChar).Value = TextBox2.Text;
            cmd.ExecuteNonQuery();
            Response.Redirect("ManageUsers.aspx");
        }

Open in new window

zhshqzycAsked:
Who is Participating?
 
s___kCommented:
CREATE PROCEDURE someprocedure @id int, @text1 as varchar(max), @text2 as varchar(max)
as
begin
update MedOrganization set OrgCode=@text1, OrgName=@text2 where id=@id
if (@@rowcount=0)
begin
Insert MedOrganization(OrgCode, OrgName) values(@OrgCode,@OrgName)
end
end
0
 
s___kCommented:
or maybe use OrgCode as identifier
0
 
zhshqzycAuthor Commented:
Can it prevent the duplication recodes because of mistakenly inserting?
0
 
s___kCommented:
@@rowcount shows the number of rows updated by the previous update statement, so if @@rowcount = 0 this means that no rows were updated and you can do Insert
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.