SQLite用触发器来替代外键约束

前端之家收集整理的这篇文章主要介绍了SQLite用触发器来替代外键约束前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

sqlite用触发器来替代外键约束

CREATE TABLE [Category] (
[Pkid] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
[CategoryName] NVARCHAR(32) NOT NULL,
[CategoryGuid] char(36) UNIQUE NOT NULL,
[CategoryDesc] nvarchar(256) NULL
)

CREATE TABLE [Product] (
[Pkid] INTEGER PRIMARY KEY AUTOINCREMENT NOT NULL,
[CategoryPkid] INTEGER NOT NULL,
[ProductName] nvarchar(32) NULL,
[ProductPrice] NUMERIC(19,4) DEFAULT '0.00' NOT NULL
)

--Insert约束
CREATE TRIGGER FK_Product_CategoryPkid_Insert
BEFORE Insert ON Product
FOR EACH ROW BEGIN
SELECT RAISE(ROLLBACK,'No this categoryPkid in category')
WHERE (SELECT Pkid FROM Category WHERE Pkid = NEW.CategoryPkid) IS NULL;
END

--Update约束 CREATE TRIGGER FK_Product_CategoryPkid_Update BEFORE Update ON Product FOR EACH ROW BEGIN SELECT RAISE(ROLLBACK,'No this categoryPkid in category') WHERE (SELECT Pkid FROM Category WHERE Pkid = NEW.CategoryPkid) IS NULL; END

猜你在找的Sqlite相关文章