如何在SQL中修改此语句?

时间:2012-09-26 21:49:14

标签: sql oracle

如何修改以下语句以从代码中删除硬编码值$ 1.00和$ 2.00并将它们放在常量表中?

sec0306_price_constants已经设置完毕。 min_price字段包含1.00,max_price字段包含2.00。

  SELECT description
    FROM l_foods
   WHERE price BETWEEN 1.00 AND 2.00
ORDER BY description

你能告诉我这样做的方法吗?

这适用于Oracle。

4 个答案:

答案 0 :(得分:3)

也许是这样的:

SELECT description
FROM l_foods
WHERE (price >= (select min_price from sec0306_price_constants )
AND price <= (select max_price from sec0306_price_constants ))
ORDER BY description

答案 1 :(得分:1)

declare @constants table (typ varchar(10), minprice float, maxprice float)

insert into @constants values 
('dirtcheap', 0.00, 0.99),
('justright', 1.00, 2.00),
('expensive', 2.01, 10.00)

select description
from   l_foods f, @constants c
where  f.price >= c.minprice and f.price <= c.maxprice
  and  c.typ = 'justright'

您可以通过不同类型的价格范围进行限定,而无需更改查询中的低值和高值 - 只需更改常量类型。

答案 2 :(得分:0)

很抱歉阅读了额外的信息,如果你有表格设置,我会按照这些方式构建:

--BEGIN PROC

DECLARE @MINPRICE DECIMAL;
DECLARE @MAXPRICE DECIMAL;

SELECT
    @MINPRICE = min_price,
    @MAXPRICE = max_price
FROM
    sec0306_price_constants;

SELECT description
    FROM l_foods
WHERE 
    price BETWEEN @MINPRICE AND @MAXPRICE
ORDER BY description

答案 3 :(得分:0)

SELECT Description, price, min_price, max_price

FROM l_foods,sec0306_price_constants

WHERE (price >= (sec0306_price_constants.min_price ) AND price <= (sec0306_price_constants.max_price ))

ORDER BY description;