我是SQL的新手,它试图编写一个存储过程来完成两件事。
我可以添加它,这是我真正遇到麻烦的第二部分。
基本上,我不明白该怎么说:“如果此插槽中的值大于x,则将其更改为该值。否则,将其更改为该值。”
我可以用任何其他语言来做到这一点,但是SQL并不能很好地引起我的共鸣。
以下基本上是我要创建的内容。前两行有效。我不知道怎么说:“从此列中读取,进行检查,然后将折后的值放入新列中。”我的想法是将值从另一列复制到我的新列中,然后从那里更改它。
CREATE OR REPLACE PROCEDURE ProductLineSale
AS
BEGIN
EXECUTE IMMEDIATE 'ALTER TABLE Product ADD SalePrice DECIMAL (6,2)';
EXECUTE IMMEDIATE 'UPDATE Product SET SalePrice = ProductStandardPrice';
IF SalePrice >= 400 THEN
SalePrice := SalePrice*.85;
ELSE
SalePrice := SalePrice*.90;
END IF;
END;
答案 0 :(得分:3)
您可以在表中添加虚拟列(虚拟列:“ values are derived rather than stored”),例如
表格和数据
create table products ( productstandardprice number( 6, 2 ) ) ;
insert into products ( productstandardprice )
select level * 199.99
from dual
connect by level <= 5 ;
查询
SQL> select * from products ;
PRODUCTSTANDARDPRICE
--------------------
199.99
399.98
599.97
799.96
999.95
ALTER TABLE
alter table products
add (
saleprice number( 6, 2 ) generated always as (
case
when productstandardprice >= 400 then
productstandardprice * .85
else
productstandardprice * .90
end
) virtual
) ;
与以前相同的查询...
SQL> select * from products ;
PRODUCTSTANDARDPRICE SALEPRICE
-------------------- ----------
199.99 179.99
399.98 359.98
599.97 509.97
799.96 679.97
999.95 849.96
过程
create or replace procedure productlinesale
is
begin
execute immediate '
alter table products
add (
saleprice number( 6, 2 ) generated always as (
case
when productstandardprice >= 400 then
productstandardprice * .85
else
productstandardprice * .90
end
) virtual
)' ;
end ;
/
Procedure created.
-- caution: this needs the "original" table (without the virtual column)
begin productlinesale; end;
/
PL/SQL procedure successfully completed.
查询测试
SQL> select
2 productstandardprice
3 , saleprice
4 , round( saleprice / productstandardprice, 2 ) as factor
5 from products
6 ;
PRODUCTSTANDARDPRICE SALEPRICE FACTOR
-------------------- ---------- ----------
199.99 179.99 .9
399.98 359.98 .9
599.97 509.97 .85
799.96 679.97 .85
999.95 849.96 .85
经过Oracle 11g和18c测试。 Dbfiddle here。
答案 1 :(得分:2)
我认为您可以在更新语句中直接使用您的逻辑。
BindCommand