简体   繁体   中英

Maximum value in column in database

In my database there is table name "Projtable". Project name contain 4 fields. 1. projct id = autoincrement (primary key) 2. projctname = varchar 3. projct_detail = varchar 4. order_id = int

now my insertion of projctname and projct_detail works perfectly. I have to find maximum value of column for orderid. How can i find this?

My code is :

-(void)insertProject:(Project *)projobj
{
//    next_orderid = next_orderid + 1;
//    projobj.orderid = next_orderid;

    NSLog(@" insert:: %@, %@, %d", projobj.outcome, projobj.projctname, projobj.orderid);
     sqlite3 *database;
    if (sqlite3_open([self.databasePath UTF8String] , &database) == SQLITE_OK)
    {
        const char *sql = "INSERT INTO proj_table (projctname, outcome, orderid) VALUES (?,?,?)";
        sqlite3_stmt *statement;
        statement = [self PrepareStatement:sql];

        int a1 = sqlite3_bind_text(statement, 1, [projobj.projctname UTF8String], -1, SQLITE_TRANSIENT);
        int a2 =  sqlite3_bind_text(statement, 2, [projobj.outcome UTF8String], -1, SQLITE_TRANSIENT);
       int a3= sqlite3_column_int( statement, 3);
        NSLog(@" integer :== %d",a3);
       // int a3 = sqlite3_bind_int(statement, 3, projobj.orderid);
            if (statement)
        {
            if (a1 != SQLITE_OK || a2 != SQLITE_OK || a3 != SQLITE_OK)
            {
                sqlite3_finalize(statement);
                return;
            }
            sqlite3_step(statement);
        }
        sqlite3_finalize(statement);
    }
}

result is 0

You find the maximum value of a column with a query like this:

SELECT MAX(orderid) FROM proj_table;

But it's better to create a column as INTEGER PRIMARY KEY (when you CREATE TABLE ), so it's autoincremented (and the last inserted id is available with sqlite3_last_insert_rowid ).

If you still have a reason to use a maximum value, ensure that SELECT MAX... and the following INSERT run in a single transaction, unless you know for certain that there will be no other processes/threads updating the database.

Use the SQL select statement

Select max(orderid) from proj_table;

you can then use the integer+1 as your next value.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM