首页 > 解决方案 > 我可以在插入语句 SQL 中使用数学公式吗?

问题描述

是否有一种可能的方法可以在插入语句 中制作数学公式,例如制作 column3 = column1 * column2

         create table orderdetails
          (orderid number(10) not null,
          productid number(10) not null,
          price float(10) not null,
          quantity number(3) not null,
          discount float(4),
          ordersize varchar2(9) not null,
          color varchar (10),
          totalprice float(5) not null,
          constraint orderid_fr2 foreign key (orderid) references orders (order_id));

insert into orderdetails values (101,3002,320,2,null,'XL','BLACK',price * quantity);

我找到了一种方法,但它只使用更新语句,每当我尝试使用 Inert 语句进行操作时,它都会给我一个错误。我只想要一个即时方法在插入方法中执行这些公式

“此处不允许列”

insert into orderdetails values (101,3002,320,2,null,'XL','BLACK',0);
update orderdetails set totalprice = price * quantity;

提前致谢。

标签: sqloracleformula

解决方案


您可以将计算作为select. 像这样的东西:

insert into orderdetails (orderid, productid, price, quantity, discount, ordersize, color, totalprice)
    select orderid, productid, price, quantity, discount, ordersize, color, price * quantity)
    from (values (101, 3002, 320, 2, null, 'XL', 'BLACK')
         ) v(orderid, productid, price, quantity, discount, ordersize, color);

并非所有数据库都支持标准values表构造函数,但都有一些方法可以创建这样的行。

也就是说,您可能只需要一个计算列。再一次,确切的语法取决于数据库,但它是这样的:

  create table orderdetails (
      orderid number(10) not null,
      productid number(10) not null,
      price float(10) not null,
      quantity number(3) not null,
      discount float(4),
      ordersize varchar2(9) not null,
      color varchar (10),
      totalprice generated always as (price * quantity),
      constraint orderid_fr2 foreign key (orderid) references orders (order_id)
);

然后,您甚至不会将值显式插入到表中。数据库会自动计算它(在插入或更新“存储”列或查询“虚拟”列时)。


推荐阅读