伙计们我想问一下如何创建触发器以在我的数据库领域进行自动增量,这是我的:
DBHelper.java
public class DBHelper extends SQLiteOpenHelper
{
public static final String TABLE_NAME = "sma";
public static final String COLUMN_ID = "_id";
public static final String COLUMN_NAMA_SMA ="nama_sma";
public static final String COLUMN_ALAMAT_SMA ="alamat_sma";
public static final String COLUMN_LATITUDE_SMA ="latitude_sma";
public static final String COLUMN_LONGITUDE_SMA ="longitude_sma";
public static final String COLUMN_TELEPON_SMA ="telepon_sma";
public static final String COLUMN_WEBSITE_SMA ="website_sma";
public static final String COLUMN_EMAIL_SMA ="email_sma";
public static final String COLUMN_TANGGAL_BERDIRI_SMA ="tanggal_berdiri_sma";
public static final String COLUMN_DESKRIPSI_SMA ="deskripsi_keunggulan_sma";
public static final String COLUMN_TANGGAL_AKREDITASI = "tanggal_akreditasi";
public static final String COLUMN_FACEBOOK ="facebook_sma";
public static final String COLUMN_TWITTER ="twitter_sma";
//foreign key
public static final String COLUMN_FK_ID_BATASAN_USIA ="id_batasan_usia";
public static final String COLUMN_FK_ID_AKREDITASI ="id_akreditasi";
public static final String COLUMN_FK_ID_LOKASI ="id_lokasi";
public static final String COLUMN_FK_ID_KURIKULUM ="id_kurikulum";
public static final String COLUMN_FK_ID_BIAYA ="id_biaya";
private static final String db_name ="schoolmap.db";
private static final int db_version=1;
private static final String db_create = "create table "
+ TABLE_NAME + "("
+ COLUMN_ID + " integer primary key autoincrement, "
+ COLUMN_NAMA_SMA + " varchar(20) not null, "
+ COLUMN_ALAMAT_SMA + " varchar(30) not null, "
+ COLUMN_LATITUDE_SMA + " varchar(10) not null, "
+ COLUMN_LONGITUDE_SMA + " varchar(10) not null, "
+ COLUMN_TELEPON_SMA + " varchar(15) null, "
+ COLUMN_WEBSITE_SMA + " varchar(20) null, "
+ COLUMN_EMAIL_SMA + " varchar(20) null, "
+ COLUMN_TANGGAL_BERDIRI_SMA + " datetime not null, "
+ COLUMN_DESKRIPSI_SMA + " varchar(30) null, "
+ COLUMN_TANGGAL_AKREDITASI + " datetime not null, "
+ COLUMN_FACEBOOK + " varchar(10) , "
+ COLUMN_TWITTER + " varchar(10), "
+ COLUMN_FK_ID_BATASAN_USIA + " integer DEFAULT 1, "
+ COLUMN_FK_ID_AKREDITASI + " integer, "
+ COLUMN_FK_ID_LOKASI + " integer, "
+ COLUMN_FK_ID_KURIKULUM + " integer, "
+ COLUMN_FK_ID_BIAYA + " integer);";
public DBHelper(Context context) {
super(context, db_name, null, db_version);
// Auto generated
}
@Override
public void onCreate(SQLiteDatabase db) {
db.execSQL(db_create);
//This code isn't working, is the code wrong?
db.execSQL("CREATE TRIGGER pk AFTER INSERT ON sma " +
"BEGIN " +
"UPDATE sma SET id_batasan_usia = id_batasan_usia + 1 " +
"END");
}
}
触发器不起作用,当我第一次运行COLUMN_FK_ID_LOKASI,并且COLUMN_FK_ID_BIAYA默认设置为0,但是在我插入第二次数据后,它必须是1吗?我之前从不使用触发器,所以这次我真的需要帮助,有人可以帮帮我吗?谢谢:D
答案 0 :(得分:0)
要将某些列的值设置为大于表中已有的任何其他值的值,请使用如下触发器:
CREATE TRIGGER autoinc_sma_lokasi
AFTER INSERT ON sma
WHEN NEW.lokasi IS NULL
BEGIN
UPDATE sma
SET lokasi = IFNULL((SELECT MAX(lokasi) FROM sma) + 1, 0)
WHERE _id = NEW._id;
END;