在SQL中用触发器编写:在插入和修改一行数据的时候自动的读出系统的时间并插入到该表的订购日期字段中。
3个回答
展开全部
楼上的答案有缺陷,只能应付一条命令影响一行记录的情形,下面的语句可能影响多条记录,该触发器处理不了:
insert Table1 select * from Table2
update Table1 set Field1=xxx where xxx(不止一行)
由此,比较完备的写法是用游标遍历改变的各行,示例如下:
假设表名叫做testIt,职工号的字段名叫做ID,类型为int,订购日期的字段名叫做DGRQ
create trigger TR_ModifyDate
on testIt
for insert, update
as
begin
if not update( DGRQ ) -- 如果正在更改DGRQ,就不进入了
begin
declare @ID int, @now datetime
set @now=getdate()
if ( select count(*) from inserted ) = 1
begin
select @ID from inserted
update testIt set DGRQ = @now where ID = @ID
end
else
begin
declare EnumInserted cursor
for select ID from inserted
for update of DGRQ
open EnumInserted
fetch EnumInserted into @ID
while @@SQLSTATUS = 0
begin
update testIt set DGRQ = @now where current of EnumInserted
fetch EnumInserted into @ID
end
close EnumInserted
deallocate cursor EnumInserted
end
end
end
insert Table1 select * from Table2
update Table1 set Field1=xxx where xxx(不止一行)
由此,比较完备的写法是用游标遍历改变的各行,示例如下:
假设表名叫做testIt,职工号的字段名叫做ID,类型为int,订购日期的字段名叫做DGRQ
create trigger TR_ModifyDate
on testIt
for insert, update
as
begin
if not update( DGRQ ) -- 如果正在更改DGRQ,就不进入了
begin
declare @ID int, @now datetime
set @now=getdate()
if ( select count(*) from inserted ) = 1
begin
select @ID from inserted
update testIt set DGRQ = @now where ID = @ID
end
else
begin
declare EnumInserted cursor
for select ID from inserted
for update of DGRQ
open EnumInserted
fetch EnumInserted into @ID
while @@SQLSTATUS = 0
begin
update testIt set DGRQ = @now where current of EnumInserted
fetch EnumInserted into @ID
end
close EnumInserted
deallocate cursor EnumInserted
end
end
end
本回答被提问者采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
CREATE TRIGGER [triggername]
ON [dbo].[tablename] FOR INSERT UPDATE
AS
declare @id int
select @id=职工号 from inserted
update tablename set 订购日期=getdate() where 职工号=@id
END
修改一下,对多条数据有效:
CREATE TRIGGER [triggername]
ON [dbo].[tablename] FOR INSERT UPDATE
AS
update tablename set 订购日期=getdate() where 职工号 in (select id from inserted)
END
ON [dbo].[tablename] FOR INSERT UPDATE
AS
declare @id int
select @id=职工号 from inserted
update tablename set 订购日期=getdate() where 职工号=@id
END
修改一下,对多条数据有效:
CREATE TRIGGER [triggername]
ON [dbo].[tablename] FOR INSERT UPDATE
AS
update tablename set 订购日期=getdate() where 职工号 in (select id from inserted)
END
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
展开全部
CREATE TRIGGER [AddInfo] ON dbo.TableA
instead of INSERT,Update
AS
declare @Data int,@Result varchar(10)
set @Data=(select Data From Inserted)
if(@Data>0)and(@Data<100)
begin
set @Result='YES'
end
else
begin
set @Result='No'
end
instead of INSERT,Update
AS
declare @Data int,@Result varchar(10)
set @Data=(select Data From Inserted)
if(@Data>0)and(@Data<100)
begin
set @Result='YES'
end
else
begin
set @Result='No'
end
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询