简体   繁体   中英

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

Is there is a possible way to make a mathimitcal formula inside an Insert statement for example making a 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);

I found a way to do it but it was only using the update statement and whenever i try to make it using the Inert statement it give me an error. I just want an instant method to do these formulas inside an insert method

"column not allowed here"

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

Thanks in advance.

You can do the calculation as part of the select . Something like this:

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

Not all databases support the standard values table constructor, but all have some method for creating a row like that.

That said, you probably just want a computed column. Once again, the exact syntax depends on the database, but it is something like this:

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

Then, you wouldn't even insert the value into the table explicitly. The database would calculate it automatically (either when inserted or updated for a "stored" column or when queried for a "virtual" column).

I'm fairly sure this isn't permitted because the column's data doesn't exist until you've inserted the row's data.

Updating it after the insert is one of the easiest ways of achieving what you want to do.

You can also use triggers to automatically do this but it can cause issues if you're working along side a code base which also stores values.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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