找了两天了,还是没找到好的解决方法,触发器,多条的update,请高手帮忙
我现在有2个表,结构一样,除了ID,其他的字段都会被修改,
所以,当修改其中一个时,其他的内容都更改
举例:表名News,字段:ID,Title,Content
ALTER TRIGGER [t_update_selfTable]
ON [dbo].[tbl_News]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
declare @Title varchar(500)
declare @Content varchar(5000)
declare @Id int
select @Id = xId, @Title = xTitle, @Content = xContent from inserted
if UPDATE(xTitle)
begin
update Smsmailboxv22.dbo.tbl_News
set
xTitle = @Title,
xContent = @Content
where xId = @Id
end
END
我写的这个,更新一条,没问题,更新2条的话,触发器执行错误,只会在另外一个表更新其中一个,很奇怪。
听说要用什么游标,现在一点都不清楚,请高手帮忙
[解决办法]
ALTER TRIGGER [t_update_selfTable]
ON [dbo].[tbl_News]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
if UPDATE(Title)
begin
update a
set
xTitle = i.Title,
xContent = i.Content
from Smsmailboxv22.dbo.tbl_News a,inserted i
where a.xId = i.Id
end
END
go
[解决办法]
ALTER TRIGGER [t_update_selfTable]
ON [dbo].[tbl_News]
AFTER UPDATE
AS
BEGIN
SET NOCOUNT ON;
declare @Title varchar(500)
declare @Content varchar(5000)
declare @Id int
if UPDATE(xTitle)
declare dd cursor for select xId, xTitle,xContent from inserted
open dd
FETCH NEXT FROM dd INTO @id, @title, @content
WHILE @@FETCH_STATUS = 0
begin
update Smsmailboxv22.dbo.tbl_News
set
xTitle = @Title,
xContent = @Content
where xId = @Id
FETCH NEXT FROM dd INTO @id, @title, @content
end
CLOSE dd
DEALLOCATE dd
END
[解决办法]
2个表之间建立级联关系,这样更新时就更方便。
[解决办法]
ALTER TRIGGER [t_update_selfTable]
ON [dbo].[tbl_News] AFTER UPDATE AS
BEGIN
update Smsmailboxv22.dbo.tbl_News
where xId=a.xId,xTitle=a.xTitle,xContent=a.xContent from inserted
END