I want to update a database in my asp.net application. The updated fields are set in textboxs.
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.ExecuteNonQuery();
cmd.CommandText = "update dbo.User_Info SET FirstName=@FirstName, LastName=@LastName,Degree=@Degree,Organization=@Organization,Phone=@Phone,Ext=@Ext where UserName =@username";
cmd.Parameters.Add("FirstName", SqlDbType.VarChar).Value = TextFirstName.Text;
cmd.Parameters.Add("LastName", SqlDbType.VarChar).Value = TextLastName.Text;
cmd.Parameters.Add("Degree", SqlDbType.VarChar).Value = TextDegree.Text;
cmd.Parameters.Add("Organization", SqlDbType.VarChar).Value = TextOrg.Text;
cmd.Parameters.Add("Phone", SqlDbType.VarChar).Value = TextPhone.Text;
cmd.Parameters.Add("Ext", SqlDbType.VarChar).Value = TextExt.Text;
However maybe some fields I don’t want to update them at all. Just leave them as blank, so how to modify the code?
For example, suppose I just want to update FirstName, the command should be
cmd.CommandText = "update dbo.User_Info SET FirstName=@FirstName where UserName =@username";
However another guy just want to update “Degree”, therefore the command will be:
cmd.CommandText = "update dbo.User_Info SET Degree=@Degree where UserName =@username";
Is there an universal command for considering various scenarios?
Universal? I doubt it. Some options:
Customize your UPDATE statements based on the inputs by dynamically adding the fields:
Change your SQL statement to check for NULL paramteres and leave the initial values if they are NULL: