- SQL code
--表名: [dbo].[tee]id int UncheckedFName nvarchar(50) UncheckedFSalary decimal(18, 0) Unchecked--表名: [dbo].[TRecordTee]id int UncheckedRecordString nvarchar(100) Unchecked
触发器recordTee 的创建
- SQL code
-- 创建一个触发器create trigger recordTee on dbo.tee after update ,insertasbegin declare @Name nvarchar(50) ; declare @Salary decimal(18,0) select @Name=i.Fname,@Salary=i.FSalary from [inserted] as i; -- [inserted]是不能变的,表示主表。 --insert insert into dbo.TRecordTee (RecordString) values('Time:'+convert(nvarchar(20),getDate(),101)+'Name:'+convert(nvarchar(10),@Name)+' salary:'+convert(nvarchar(10),@Salary)); --select * from dbo.TRecordTee;end
--试试:
- SQL code
insert into dbo.tee(FName,Fsalary)values('mmm',5000);goselect *from dbo.tee;
请问:
- SQL code
--现在 国家规定: --要求工资一定要 大于 1500元/月; 如何 修改 触发器[recordTee] 使得插入,or 修改的表[dbo.tee]的工资 Fsalary<=1500时, 就不允许输入?
------解决方案--------------------
- SQL code
-- 创建一个触发器create trigger recordTee on dbo.tee after update ,insertasbegin declare @Name nvarchar(50) ; declare @Salary decimal(18,0) select @Name=i.Fname,@Salary=i.FSalary from [inserted] as i; -- [inserted]是不能变的,表示主表。 --insert if @Salary>1500 begin insert into dbo.TRecordTee (RecordString) values('Time:'+convert(nvarchar(20),getDate(),101)+'Name:'+convert(nvarchar(10),@Name)+' salary:'+convert(nvarchar(10),@Salary)); --select * from dbo.TRecordTee; end end
------解决方案--------------------
那用 INSTEAD OF 替换 AFTER
------解决方案--------------------
- SQL code
-- 创建一个触发器create trigger recordTee on dbo.tee INSTEAD OF update ,insertasbegin declare @Name nvarchar(50) ; declare @Salary decimal(18,0) select @Name=i.Fname,@Salary=i.FSalary from [inserted] as i; -- [inserted]是不能变的,表示主表。 --insert if @Salary>1500 begin insert into dbo.tee(FName,Fsalary)values('mmm',5000); insert into dbo.TRecordTee (RecordString) values('Time:'+convert(nvarchar(20),getDate(),101)+'Name:'+convert(nvarchar(10),@Name)+' salary:'+convert(nvarchar(10),@Salary)); --select * from dbo.TRecordTee; end end
------解决方案--------------------
- SQL code
create trigger recordTee on dbo.tee for update ,insertasbegin declare @Name nvarchar(50) ; declare @Salary decimal(18,0) select @Name=i.Fname,@Salary=i.FSalary from [inserted] as i; -- [inserted]是不能变的,表示主表。 if @salary>=1500 begin insert into dbo.TRecordTee (RecordString) values('Time:'+convert(nvarchar(20),getDate(),101)+'Name:'+convert(nvarchar(10),@Name)+' salary:'+convert(nvarchar(10),@Salary)); end else beginprint '工资不能少于1500元'end --select * from dbo.TRecordTee;end
------解决方案--------------------
触发器比较费劲,用约束简单
- SQL code
create table [dbo].[tee](id int,FName nvarchar(50),FSalary decimal(18, 0))ALTER TABLE [dbo].[tee]ADD CONSTRAINT chk_tee CHECK (FSalary>1500)insert into [tee] select 1,'aaaa',1000------------------消息 547,级别 16,状态 0,第 1 行INSERT 语句与 CHECK 约束"chk_tee"冲突。该冲突发生于数据库"Test",表"dbo.tee", column 'FSalary'。语句已终止。