MS SQL 触发器问题

mlmary 2003-08-21 10:35:14
两个表结构相同——

CREATE TABLE [test] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[姓名] [varchar] (8) COLLATE Chinese_PRC_CI_AS NULL ,
[年龄] [int] NULL ,
CONSTRAINT [PK_test] PRIMARY KEY CLUSTERED
(
[id]
) ON [PRIMARY]
) ON [PRIMARY]
GO

CREATE TABLE [tests] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[姓名] [varchar] (8) COLLATE Chinese_PRC_CI_AS NULL ,
[年龄] [int] NULL ,
CONSTRAINT [PK_tests] PRIMARY KEY CLUSTERED
(
[id]
) ON [PRIMARY]
) ON [PRIMARY]
GO


PS:两个表仅是做实验用,就别问俺“为啥建两个相同表”了

数据也相同

姓名 年龄
----------------------
张三 1
李四 2
王五 3
赵六 4


在test表上建触发器

CREATE TRIGGER testtri ON dbo.test
FOR UPDATE
AS
update tests set
姓名=inserted.姓名,
年龄=inserted.年龄
from tests,deleted,inserted
where tests.姓名=deleted.姓名


问题来了——

执行
update test set 年龄=年龄+1 where 姓名='张三'
不会有问题,tests表中的张三的年龄可以变

但是,如果执行
update test set 年龄=年龄+1
就惨了,tests表中的四行数据全都变成赵六的了

为什么呀?是我对触发器理解错了吗?
请大家帮忙指点指点吧,谢谢
...全文
39 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
chenqinzeng 2003-08-22
  • 打赏
  • 举报
回复
这个也是很容易的,编写触发器的时候deleted是存放删除掉的记录和修改过旧的记录,而inserted是存放新增加的数据和修改过新的数据,这下你应该可以自己搞定了吧
mlmary 2003-08-21
  • 打赏
  • 举报
回复
为什么 chenqinzeng(chenqinzeng) 和 happy_0325(快乐) 都要使用 “where tests.姓名=inserted.姓名”呢

如果这样写的话,执行update test set 姓名=姓名 + '人'的话,就不对了

happy_0325 2003-08-21
  • 打赏
  • 举报
回复
CREATE TRIGGER testtri ON dbo.test
FOR UPDATE
AS
update tests set
姓名=inserted.姓名,
年龄=inserted.年龄
from tests,inserted
where tests.姓名=inserted.姓名
mlmary 2003-08-21
  • 打赏
  • 举报
回复
where tests.姓名=inserted.姓名
?
但是如果我update了姓名的值的话这样就会出错呀?
chenqinzeng 2003-08-21
  • 打赏
  • 举报
回复
在test表上建触发器

CREATE TRIGGER testtri ON dbo.test
FOR UPDATE
AS
update tests set
姓名=inserted.姓名,
年龄=inserted.年龄
from tests,deleted,inserted
where tests.姓名=inserted.姓名


就行了,因为update test set 年龄=年龄+1执行之后
表deleted内容如下:
张三 1
李四 2
王五 3
赵六 4
表inserted内容如下:
张三 2
李四 3
王五 4
赵六 5

mlmary 2003-08-21
  • 打赏
  • 举报
回复
大力大大,可以不用ID这个字段吗?
为什么用tests.姓名=deleted.姓名不行呢?
pengdali 2003-08-21
  • 打赏
  • 举报
回复
CREATE TABLE [test] (
[id] [int] IDENTITY (1, 1) NOT NULL ,
[姓名] [varchar] (8) COLLATE Chinese_PRC_CI_AS NULL ,
[年龄] [int] NULL ,
CONSTRAINT [PK_test] PRIMARY KEY CLUSTERED
(
[id]
)
)
GO

CREATE TABLE [tests] (
[id] [int] ,
[姓名] [varchar] (8) COLLATE Chinese_PRC_CI_AS NULL ,
[年龄] [int] NULL ,
CONSTRAINT [PK_tests] PRIMARY KEY CLUSTERED
(
[id]
),
FOREIGN KEY (FK_ID) REFERENCES test (id)
)
GO



CREATE TRIGGER testtri ON dbo.test
FOR UPDATE
AS
update tests set 姓名=inserted.姓名, 年龄=inserted.年龄 from inserted where tests.id=inserted.id
go
helodd 2003-08-21
  • 打赏
  • 举报
回复
你都没有条件,肯定update 所有的.
update test set 年龄=年龄+1
where 姓名 in select 姓名 from inserted
aierong 2003-08-21
  • 打赏
  • 举报
回复
up

34,590

社区成员

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

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