《触发器练习》
(
cardID  CHAR(10)primary key,--卡号
customerName CHAR(8)NOT NULL,--顾客姓名
currentMoney MONEY NOT NULL-- 当前余额
)
CREATE TABLE transInfo  --交易信息表
(
cardID  CHAR(10) NOT NULL,    --卡号
transType  CHAR(4) NOT NULL,  --交易类型(存入/支取)
transMoney  MONEY NOT NULL,  --交易金额
transDate  DATETIME NOT NULL --交易日期默认为当天日期
CONSTRAINT DF_transDate DEFAULT(getDate( ))
)
GO
/*--插入测试数据:张三开户,开户金额为1000 ;李四开户,开户金额1 ---*/sql触发器的使用
INSERT INTO bank(customerName,cardID,currentMoney) V ALUES('张三','1001 0001',1000) INSERT INTO bank(customerName,cardID,currentMoney) V ALUES('李四','1001 0002',1)
完成下列操作:
1.建INSERT触发器:在交易信息表transInfo上创建插入触发器。根据交易类型是支取/存入,减少或增加帐户表(bank)中对应卡号的余额,如果支取的金额小于1,则显示交易失败,撤销刚才的操作,否则修
改信息表的信息。
程序代码:
CREA TE TRIGGER transInfo_INSERT
ON transInfo AFTER INSERT
AS
BEGIN
DECLARE @transMoney MONEY--交易金额
DECLARE @CARD CHAR(10)--交易的卡号
DECLARE @currentMoney MONEY--现金
DECLARE @transType CHAR(4)--交易类型
SET @transType=(SELECT transType FROM INSERTED)
SET @transMoney=(SELECT transMoney FROM INSERTED)
SET @CARD=(SELECT cardID FROM INSERTED)
IF(@transType='存入')
BEGIN
UPDA TE bank SET currentMoney=currentMoney+@transMoney
WHERE cardID=@CARD
SET @currentMoney=(SELECT currentMoney FROM BANK
WHERE cardID=@CARD)
PRINT'交易成功!交易金额:'+CONVERT(CHAR,@transMoney)
PRINT'卡号:'+@CARD+'余额:'+CONVERT(CHAR,@currentMoney)
END
ELSE IF( @transType='支取')
IF( @transMoney<1)
BEGIN
PRINT'交易失败'
ROLLBACK TRANSACTION
END
ELSE
BEGIN
UPDA TE bank SET currentMoney=currentMoney-@transMoney
WHERE cardID=@CARD
SET @currentMoney=(SELECT currentMoney FROM BANK
WHERE cardID=@CARD)
SET @transMoney=-@transMoney
PRINT'交易成功!交易金额:'+CONVERT(CHAR,@transMoney)
PRINT'卡号:'+@CARD+'余额:'+CONVERT(CHAR,@currentMoney)
END
END测试数据:
DELETE FROM transInfo
SET NOCOUNT ON
INSERT INTO transInfo(cardID,transType,transMoney)VALUES('1001 0001','支取',200)
INSERT INTO transInfo(cardID,transType,transMoney)VALUES('1001 0002','存入',50000)
运行结果:
2.创建DELETE 触发器:在交易信息表transInfo上创建删除触发器,如果删除交易信息表的记录,将删除的记录备份到backupT able表中。
程序代码:
CREATE TRIGGER transInfo_DELETE
ON transInfo AFTER DELETE
AS
BEGIN
PRINT'开始备份数据,请稍后...'
SELECT*INTO backupTable FROM DELETED
PRINT'备份数据成功'
END
测试命令如下:
DELETE FROM transInfo
运行结果:
3.创建UPDATE触发器:在帐户信息表bank上创建更新触发器, 要求每笔交易金额超过2万元,则交易失败。
程序代码:
CREA TE TRIGGER transInfo_UPDA TE
ON BANK AFTER UPDA TE
AS
BEGIN
DECLARE transMoney MONEY--交易金额
SET@transMoney=(SELECT currentMoney FROM INSERTED)-(SELECT currentMoney FROM DELETED)
IF ABS(@transMoney)>20000
BEGIN
PRINT'交易金额:'+CONVERT(CHAR,@MON1)
ROLLBACK TRANSACTION
END
END
测试命令如下:
SET NOCOUNT ON
UPDATE BANK
SET currentMoney=currentMoney+25000
WHERE CARDID='1001 0001'
INSERT INTO transInfo(cardID,transType,transMoney)VALUES('1001 0002','支取',30000)
INSERT INTO transInfo(cardID,transType,transMoney)VALUES('1001 0002','存入',500)

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。