我需要编写一个DROP COLUMN例程来操作SQLite数据库。
它会被称为:
dropColumn("SomeTable", "SomeColumn");
SQLite FAQ说要删除列,您必须创建一个只包含所需列的临时表,然后将数据复制到其中,然后重命名。
将它封装到例程中应该不会太难。但看起来写它会有点烦人。
当然有人已经写过这样的例行公事了。如果是的话,我可以偷走它吗? :)
答案 0 :(得分:5)
这里有一些伪代码:
columnNameList = ""
newTableStr = "CREATE TABLE tempMyTable ("
execute statement: "PRAGMA table_info('MyTable')"
While looping through RecordSet
If RecordSet.name != tableRowToDeleteName
If columnNameList != "" Then columnNameList += ","
columnNameList += RecordSet.name
newTableStr += RecordSet.name + " " + RecordSet.type
If RecordSet.notnull Then
newTableStr += " NOT NULL"
End If
If RecordSet.dflt_value != "" Then
newTableStr += " DEFAULT(" + RecordSet.dflt_value + ")"
End If
If Not Last Record in RecordSet
newTableStr += ","
End If
End If
End Loop
newTableStr += ");"
execute statement: newTableStr
execute statement: "INSERT INTO tempMyTable (" + columnNameList + ")" +
"SELECT " + columnNameList + " FROM MyTable;"
Delete table: MyTable
Rename Table: tempMyTable to MyTable