db2触发器中,如何写满足条件弹出提示框或者抛出错误?
发布网友
发布时间:2022-04-26 14:15
我来回答
共1个回答
热心网友
时间:2022-04-07 22:41
SIGNAL SQLSTATE '75002' ('ID不能为空') ;
测试成功的执行代码如下:
db2 => CREATE TRIGGER AfterInsertDetail \
db2 (cont.) => AFTER INSERT ON OrderDetail \
db2 (cont.) => REFERENCING NEW AS N \
db2 (cont.) => FOR EACH ROW MODE DB2SQL \
db2 (cont.) => BEGIN ATOMIC \
db2 (cont.) => DECLARE v_nowCount INT; \
db2 (cont.) => SET v_nowCount = \
db2 (cont.) => (SELECT Amount FROM Goods \
db2 (cont.) => WHERE ID = N.GoodsID ); \
db2 (cont.) => IF v_nowCount - N.Amount < 0 THEN \
db2 (cont.) => SIGNAL SQLSTATE '75002' ('库存不足!') ; \
db2 (cont.) => ELSE \
db2 (cont.) => UPDATE \
db2 (cont.) => Goods \
db2 (cont.) => SET \
db2 (cont.) => Amount = Amount - N.Amount \
db2 (cont.) => WHERE \
db2 (cont.) => ID = N.GoodsID; \
db2 (cont.) => END IF; \
db2 (cont.) => END
DB20000I SQL 命令成功完成。
db2 => INSERT INTO OrderDetail VALUES(1, 1, 90)
DB20000I SQL 命令成功完成。
db2 => INSERT INTO OrderDetail VALUES(1, 1, 20)
DB21034E 该命令被当作 SQL 语句来处理,因为它是无效的“命令行处理器”命令。在
SQL 处理期间,它返回:
SQL0438N 应用程序发生错误或警告,其诊断文本为:"库存不足!"。 SQLSTATE=75002
db2 => select * from goods
ID AMOUNT
----------- -----------
1 10
1 条记录已选择。
db2 => select * from OrderDetail
ID GOODSID AMOUNT
----------- ----------- -----------
1 1 90
1 条记录已选择。