我需要编写一个DROP COLUMN例程来处理SQLite数据库。
它会被这样称呼:
dropColumn("SomeTable", "SomeColumn");
SQLite FAQ说,要删除列,您必须创建一个仅包含所需列的临时表,然后将数据复制到该表中,然后重命名。
将其封装到例程中应该并不难。但是看起来写起来有点烦人。
肯定有人在那里已经编写了这样的例程。如果是这样,我可以偷吗? :)
最佳答案
以下是一些伪代码供您使用:
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