0
SqlConnection sqlcon = new SqlConnection(GlobalClass.DBLocate);
sqlcon.Open();

string query = "Delete from [Plans] Where Date < '" + 
GlobalClass.Date.ToShortDateString() + "'";

SqlDataAdapter sda = new SqlDataAdapter(query, sqlcon);

sda.SelectCommand.ExecuteNonQuery();

I have tried many techniques but everything in this database is deleted or nothing at all. Many thanks

  • Possible duplicate of [What are good ways to prevent SQL injection?](https://stackoverflow.com/questions/14376473/what-are-good-ways-to-prevent-sql-injection) – mjwills Apr 06 '18 at 13:27
  • You should format your date accordingly to the regional settings or ansi std YYYYMMDD – McNets Apr 06 '18 at 13:30

2 Answers2

0

Instead of passing in the date as a string, why don't you write the SQL using it's native date functions?

As this question is tagged as C# and not with any specific flavor of SQL, I am writing this connecting to SQL Server. You also did not provide the DDL for the table that is being deleted from. The code is based on using a proper column type for the [Date] column, which would be some variant of DateTime.

The following statement should delete everything up the current DateTime

string query = "DELETE from [Plans] WHERE Date < GetDate()";

If you need to fine tune this to everything before today, then you can use CAST/CONVERT and just get the Date portion:

string query = "DELETE from [Plans] WHERE Date < Cast(GetDate() as Date)";

You also don't need to use a DataAdapter for a NonQuery; it's return type is an int, and can be assinged directly

int RowsDeleted = cmd.ExecuteNonQuery();

So putting it all together, we get this code block. I also wrapped within a using block so that the resources are properly cleaned up afterwards.

int RowsDeleted = -1;

using (SqlConnection sqlcon = new SqlConnection(GlobalClass.DBLocate)) {
    string query = "DELETE from [Plans] WHERE Date < GetDate()";
    SqlCommand cmd = new SqlCommand(query, sqlcon);

    sqlcon.Open();
    RowsDeleted = cmd.ExecuteNonQuery();
    sqlcon.Close();
}
Mad Myche
  • 1,075
  • 1
  • 7
  • 15
-1

Try this. I guess your date value is to new, and hence deletes everything.

SqlConnection sqlcon = new SqlConnection(GlobalClass.DBLocate);
sqlcon.Open();

DateTime yesterday = DateTime.Today.AddDays(-1);

string query = "Delete from [Plans] Where Date <= '" + 
yesterday.ToShortDateString() + "'";

SqlDataAdapter sda = new SqlDataAdapter(query, sqlcon);

sda.SelectCommand.ExecuteNonQuery();
andreasnico
  • 1,478
  • 14
  • 23