请问!如何用触发器实现如下功能:

songless 2000-07-19 04:46:00
对某个表的某个行进行更新/增加,触发器只对更新的行起作用。
...全文
218 6 打赏 收藏 转发到动态 举报
写回复
用AI写文章
6 条回复
切换为时间正序
请发表友善的回复…
发表回复
songless 2000-07-20
  • 打赏
  • 举报
回复
你们,能告诉我以下代码如何该,能实现增加时x4=9,修改时x4=9(修改时不能产生新记录),谢谢

CREATE Trigger ChooseValue On Test1
For Update,Insert
As
Declare @InsertedCount Int
Declare @DeletedCount Int

Set @InsertedCount=(Select Count(*) From inserted)
Set @DeletedCount=(Select Count(*) From deleted)

If (@InsertedCount>0) Begin
Insert Test1 (x1,x4) Values ("2","9")
End

Else If(@DeletedCount>0) Begin
Update Test1 Set x4="4"
From Test1,Deleted
where Test1.x1=Deleted.x1
End
Wingsun 2000-07-20
  • 打赏
  • 举报
回复
CREATE Trigger ChooseValue On Test1
For Update,Insert
As
if exists(select * from deleted)
update test1 set x4 = "4" from test1, inserted where test1.x1 = inserted.x1 And test1.x4=inserted.x4
else
update test1 set x4 = "9" from test1, inserted where test1.x1 = inserted.x1 And test1.x4=inserted.x4
huntout 2000-07-20
  • 打赏
  • 举报
回复

CREATE Trigger ChooseValue On Test1
For Update,Insert
As
if exists(select * from deleted)
update test1 set x4 = "4" from test1 t, inserted i where t.x1 = i.x1
else
update test1 set x4 = "9" from test1 t, inserted i where t.x1 = i.x1
Wingsun 2000-07-19
  • 打赏
  • 举报
回复
如下:
CREATE TRIGGER [Update Employee] ON dbo.Employee
FOR UPDATE
AS
Update Salary Set Salary.ID=Inserted.ID,
Salary.DepID=Inserted.DepID,
Salary.Name=Inserted.Name,Salary.Status=Inserted.Status From Inserted,deleted
Where deleted.DepID=salary.depid and deleted.id=salary.id

huntout 2000-07-19
  • 打赏
  • 举报
回复
The deleted table stores copies of the affected rows during DELETE and UPDATE statements. During the execution of a DELETE or UPDATE statement, rows are deleted from the trigger table and transferred to the deleted table. The deleted table and the trigger table ordinarily have no rows in common.

The inserted table stores copies of the affected rows during INSERT and UPDATE statements. During an INSERT or UPDATE transaction, new rows are added simultaneously to both the inserted table and the trigger table. The rows in the inserted table are copies of the new rows in the trigger table.

An UPDATE transaction is like a delete followed by an insert; the old rows are copied to the deleted table first, and then the new rows are copied to the trigger table and to the inserted table.

leslielu 2000-07-19
  • 打赏
  • 举报
回复
在表更新或删除的时候会生成一个系统表,你要在触发器里读取这个系统表,
如你删除时建DELETEd表,添加时在INSERTed表内写入数据
一个典型的例子。
creat trigger delete_artists
on Recordings
for delete as
begin
delete Artists from artists,deleted
where artist.artist_id = deleted.artist_id
end
go

34,576

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧