I am using following C# method to execute SQL queries:
public bool ExecuteQuery(String pQuery)
{
SqlConnection con = new SqlConnection("MyConnectionString");
con.Open();
SqlTransaction trans = con.BeginTransaction(IsolationLevel.ReadCommitted);
try
{
SqlCommand cmd = new SqlCommand(pQuery, con, trans);
cmd.ExecuteNonQuery();
trans.Commit();
con.Close();
trans.Dispose();
return true;
}
catch (Exception exp)
{
trans.Rollback();
con.Close();
MessageBox.Show(exp.Message, "Error!!", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
return false;
}
When I pass this statement:
ExecuteQuery("DROP TABLE MyTable");
then the method returns true, which means it worked fine, but when I check SQL Server, myTable
was not dropped. If I run the same statement in SQL Server Management Studio, MyTable
is dropped...
Where am I wrong?
Before answering your question, some comments:
Avoid coding such operations using query text, this is a high chance you can get problems with security. Better create stored procedure that executes table drop:
Then pass the stored procedure's name as parameter to your function. Now back to your error.
Table drop is not a transaction, but you try to execute it in transactional schema. This makes it fail. Try: