...of update触发器,实现:当从表scor
编辑: admin 2017-23-02
-
4
CREATE TABLE score (
id INT PRIMARY KEY,
val VARCHAR(10)
);
CREATE TRIGGER tr_Update_score
ON score
instead of update
AS
BEGIN
IF USER_NAME() = 'dbo'
UPDATE
score
SET
score.val = inserted.val
FROM
score JOIN inserted
ON (score.id = inserted.id)
ELSE
PRINT '你不是 DBO!';
END;
insert into score VALUES(1, 'A');
-- 使用 Demo 作为用户名,登录到数据库。
E:\>sqlcmd -S "localhost\SQLEXPRESS" -U Demo -P demo
1> use testwork
2> go
已将数据库上下文更改为 'TestWork'。
1> UPDATE score SET val='B' WHERE id = 1;
2> go
(1 行受影响)
你不是 DBO!
1> select * FROM score;
2> go
id val
----------- ----------
1 A
(1 行受影响)
-- 使用操作系统验证,登录到数据库。
E:\>sqlcmd -S "localhost\SQLEXPRESS"
1> use testwork
2> go
已将数据库上下文更改为 'TestWork'。
1> UPDATE score SET val='B' WHERE id = 1;
2> go
(1 行受影响)
1> select * FROM score;
2> go
id val
----------- ----------
1 B
(1 行受影响)
======================
--货物表
CREATE TABLE stock(
id INT,
stock_amount INT
);
--订单表
CREATE TABLE sell(
ID INT,
GoodsID INT,
sell_amount INT
);
-- 库存测试数据:
INSERT INTO stock VALUES (1, 100);
create trigger trgAfterSell
on sell
after insert
as
begin
declare
@cGoodsID as int,
@sell_amount as int,
@nowCount as INT
select @cGoodsID = GoodsID, @sell_amount = sell_amount
from inserted
SELECT @nowCount = stock_amount
FROM stock
where ID = @cGoodsID;
IF @nowCount - @sell_amount < 0
BEGIN
PRINT '库存量不足,只有 ' + CAST(@nowCount AS varchar);
ROLLBACK;
END
ELSE
BEGIN
update stock
set stock_amount = stock_amount - @sell_amount
where ID = @cGoodsID
PRINT '库存量还剩余' + CAST ((@nowCount - @sell_amount) AS varchar);
END
end
1> INSERT INTO sell VALUES(1, 1, 90);
2> go
(1 行受影响)
库存量还剩余10
1> INSERT INTO sell VALUES(1, 1, 20);
2> go
库存量不足,只有 10
消息 3609,级别 16,状态 1,服务器 HOME-BED592453C\SQLEXPRESS,第 1 行
事务在触发器中结束。批处理已中止。
1> select * from sell;
2> select * from stock;
3> go
ID GoodsID sell_amount
----------- ----------- -----------
1 1 90
(1 行受影响)
id stock_amount
----------- ------------
1 10
(1 行受影响)