我可以在插入语句 SQL 中使用数学公式吗?

can i use a mathemtical formula in an insert into statement SQL?

是否有可能在 Insert 语句 中创建数学公式 例如制作 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);

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

"column not allowed here"

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

提前致谢。

我很确定这是不允许的,因为在您插入行的数据之前,该列的数据不存在。

在插入后更新它是实现您想要执行的操作的最简单方法之一。

您也可以使用触发器自动执行此操作,但如果您在同时存储值的代码库中工作,它可能会导致问题。

您可以将计算作为 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 table 构造函数,但所有数据库都有一些创建这样的行的方法。

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

  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)
);

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