触发更新列的总和?(Trigger to update sum of columns?)

系统教程 行业动态 更新时间:2024-06-14 16:57:17
触发更新列的总和?(Trigger to update sum of columns?)

我知道这不是一种方法,但这是一个面试问题

使用触发器更新total = marks1 + marks2 + marks3。

我写了类似的东西,但是在插入语句后它没有更新。

CREATE table marks ( marks1 int, marks2 int, marks3 int, total int ) SELECT * from marks m insert into marks values(10,10,20,0) drop TRIGGER total_marks create TRIGGER total_marks ON marks AFTER INSERT AS begin SET NOCOUNT ON DECLARE @marks1 as int select @marks1 = inserted.marks1 FROM inserted DECLARE @marks2 as int select @marks1 = inserted.marks2 FROM inserted DECLARE @marks3 as int select @marks1 = inserted.marks3 FROM inserted DECLARE @result as int set @result = @marks1 + @marks2 + @marks3 update marks set total = @result SET NOCOUNT OFF end

I know this is not a way to do it but it's a interview question

to update total = marks1 + marks2 + marks3 using a trigger.

I wrote something like this but it's not updating after an insert statement.

CREATE table marks ( marks1 int, marks2 int, marks3 int, total int ) SELECT * from marks m insert into marks values(10,10,20,0) drop TRIGGER total_marks create TRIGGER total_marks ON marks AFTER INSERT AS begin SET NOCOUNT ON DECLARE @marks1 as int select @marks1 = inserted.marks1 FROM inserted DECLARE @marks2 as int select @marks1 = inserted.marks2 FROM inserted DECLARE @marks3 as int select @marks1 = inserted.marks3 FROM inserted DECLARE @result as int set @result = @marks1 + @marks2 + @marks3 update marks set total = @result SET NOCOUNT OFF end

最满意答案

您的触发器不处理多行插入,将所有行更新为相同的值(而不仅仅是插入的行),并且远比必要复杂得多。 你的钥匙在哪里?

CREATE TRIGGER dbo.total_marks ON dbo.marks FOR INSERT AS BEGIN SET NOCOUNT ON; UPDATE m SET total = i.marks1 + i.marks2 + i.marks3 FROM dbo.marks AS m INNER JOIN inserted AS i ON m.key = i.key; END GO

如果你的表真的没有密钥(它对我来说没有多大意义),那么你可以这样说,但它可能会更新已更新的行:

ON m.marks1 = i.marks1 AND m.marks2 = i.marks2 AND m.marks3 = i.marks3 WHERE m.total = 0;

Your trigger doesn't handle multiple row inserts, updates all rows to the same value (rather than just the row(s) inserted), and is far more complex than necessary anyway. Where is your key?

CREATE TRIGGER dbo.total_marks ON dbo.marks FOR INSERT AS BEGIN SET NOCOUNT ON; UPDATE m SET total = i.marks1 + i.marks2 + i.marks3 FROM dbo.marks AS m INNER JOIN inserted AS i ON m.key = i.key; END GO

If your table really doesn't have a key (it doesn't make a whole lot of sense to me), then you can say this, but it may update rows that were already updated:

ON m.marks1 = i.marks1 AND m.marks2 = i.marks2 AND m.marks3 = i.marks3 WHERE m.total = 0;

更多推荐

本文发布于:2023-04-12 19:50:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/dzcp/c523ea8eb0e6a8f39f0c16cdbadce271.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:总和   Trigger   update   sum   columns

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!