tags:

views:

386

answers:

2

Hi, I need to run two statements like so:

Select amount from db where ID=5
DELETE from db where ID=5

Currently I prepair a run two different statements. I wonder if there is a way to combine it in on statement.

Basically all I need to do is to get and amount column from the row before is is deleted.

thanks

+5  A: 

SQLite does not support this extension to standard SQL -- you do have to use both statements, SELECT first, DELETE next. You can wrap them in a transaction, of course, (BEGIN and COMMIT statements before and after will guarantee that), to guarantee atomicity and consistency.

Alex Martelli
A: 

You can do this by separating the two statements with a semicolon, e.g. (using the .NET port of SQLite):

using (SQLiteConnection conn = new SQLiteConnection("Data Source=fie.db3"))
{
  conn.Open();

  using (var cmd = conn.CreateCommand())
  {
    cmd.CommandText = "SELECT id FROM fies; DELETE FROM fies WHERE id = 5;";
    using (var reader = cmd.ExecuteReader())
    {
      while (reader.Read())
      {
        Console.WriteLine(reader[0]);
      }
    }
  }
}
itowlson
All this will do is execute one statement and then the other. It does not make it atomic. Another process could modify the database in between the SELECT and the DELETE. The only way to guard against that is to wrap them in a transaction.
finnw
I have tried the combining statement (not transactionally) and run in the SQLite manager (an add-on to Firefox). This what i had:"SELECT amount FROM table where id = 5; DELETE FROM fies WHERE id = 5;"command exectued, row was deleted, but nothing was returned from the combined statetement
leon
Forgot to add: this is for iPhone embedded SQLite - so this may be a difference with combine statements. Can it?
leon
Leon: Yes, this could be a difference in implementations. I tested it with SQLite.NET; it definitely returns the result of the SELECT there.
itowlson
finnw: so wrap them in a transaction: conn.BeginTransaction(). Having a transaction doesn't stop you using a combined SQL statement.
itowlson