繁体   English   中英

如何在行中的sql中乘以两个值并将结果放在同一行中的另一个单元格中?

[英]How can multiply two value in sql in row and put the result in the another cell in the same row?

我有一张名为'Task'的表

有四列(id,x,y和x * y)

我只输入值(id,x和y)

当我输入值时需要触发器或其他东西自动计算值'x * y'

谢谢 ,

在SQL Server中,您可以只使用计算列 ,不需要触发器;

CREATE TABLE task (
  id INT,
  x  INT, 
  y  INT,
  xy AS x*y);  -- xy will always be selected as x*y

一个要测试的SQLfiddle

其他数据库具有类似的功能,例如Oracle的虚拟列

您可以使用Computed列来实现目标。

CREATE TABLE Task(Id int, x int, y int, xy as x* y);

如果你确实需要一个触发器(可能以后可以更改值, x*y只是默认值?),那么可以这样做:

CREATE TRIGGER T_task on task
instead of insert
as
    insert into task (id,x,y,[x*y] /* Really need to rename this */)
    select id,x,y,x*y from inserted

请参阅使用inserted和deleted表

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM