How to delete records with SqlCommand

This code shows you how to delete records with an SQL statement and get the number of records deleted returned back as an integer.

SqlConnection con = new SqlConnection(ConfigurationSettings.AppSettings["con"]);
SqlCommand cmd = new SqlCommand();
cmd.CommandText = "DELETE FROM EmployeesCopy WHERE TitleofCourtesy='Mr.'";
cmd.Connection = con;
int numberDeleted = cmd.ExecuteNonQuery();
Response.Write(numberDeleted.ToString() + " employees were deleted.<br>");
// use this instead of the above line if we're in a windows form rather than an ASP.NET page
//MessageBox.Show(numberDeleted.ToString() + " employees were deleted.<br>");

You might also like...


Edward Tanguay Edward Tanguay updates his personal web site weekly with code, links, quotes and thoughts on web development. Sign up for the free newsletter.


Why not write for us? Or you could submit an event or a user group in your area. Alternatively just tell us what you think!

Our tools

We've got automatic conversion tools to convert C# to VB.NET, VB.NET to C#. Also you can compress javascript and compress css and generate sql connection strings.

“In order to understand recursion, one must first understand recursion.”