How to delete Multiple row from one table in sqlite iOS?

北战南征 提交于 2019-12-13 22:14:50

问题


I have a table, MessageTable in sqlite.I want to delete selected rows from it. How can I achieve that. I have searched hard but didn't get any suitable answer. Any help would be appreciated. TIA.


回答1:


If you want to delete the multiple selected rows from a table, IN clause will be the one of the best choice. While deleting the rows you need to take care what kind of column you are going to mention in the condition.

Here are the various data types mentioned how to delete the set of rows from a table.

For Numbers:

NSString *query = [NSString stringWithFormat:@"DELETE FROM Messages WHERE ID IN (101,102,103,104)];;

Here for Numbers or Integers, we can set the Array of Numbers directly to the query or we can set as comma separated values.

Accommodating array in the Query.

NSArray *idArraysToDelete = @[101, 102, 103, 104];
NSString *query = [NSString stringWithFormat:@"DELETE FROM Messages WHERE (ID IN %@)", idArraysToDelete];

For Strings:

Lets say you want to delete the messages of few selected peoples,

NSMutableArray *parameters = [NSMutableArray new];
for (id avatar in avatarNames) {
    if (avatar != [NSNull null]) {
        if ([avatar isKindOfClass:[NSString class]]) {
            NSString *strValue = [NSString stringWithFormat:@"'%@'", avatar];
            [parameters addObject:strValue];
        } else {
            [parameters addObject:bindVal];
        }
    }
}
NSString *deleteQuery = [NSString stringWithFormat:@"DELETE FROM Messages WHERE AVATAR IN (%@)", tableName, columnName, [parameters componentsJoinedByString:@","]];

Here for Strings, SQLite always assumes the VARCHAR or String may contain UNICode characters, So while setting the parameters we are setting single quote('') for each values. SQLite will assume the value mentioned in the single quotes are the row values. In general for any condition check on strings, single quotes are mandatory




回答2:


If you want to delete selected rows then may be "in" can help you. try this code:

Delete from MessageTable WHERE MSG_ID in (1,2,4,5,7);

MSG_ID is your unique id of row and pass selected rows id in ("SELCECTED_ROWS_HERE")*



来源:https://stackoverflow.com/questions/38561266/how-to-delete-multiple-row-from-one-table-in-sqlite-ios

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!