drop procedure if exists p2; delimiter $$ create procedure p2($start date,$en date,$cusid varchar(20)) begin set @sql=concat(' create or replace view v1 as select orderdate,sum(amount) as amt from orderitems a join orders b using(Orderid) where orderdate between ',$start,' and ',$en,' and customerid="',$cusid,'" group by orderdate'); prepare stmt from @sql; execute stmt; if(day($start)>day($en)) then set $start=concat(year($start),month($start),day($en)); end if; with recursive tmp as( select $start as ls,timestampadd(month,1,$start) as es,year($start) as y,month($start) as m,if(sum(amt) is null,0,sum(amt)) as amt from v1 where year(orderdate)=year($start) and month(orderdate)=month($start) union all select b.es as ls,timestampadd(month,1,b.es) as es,year(timestampadd(month,1,b.es)) as y,month(timestampadd(month,1,b.es)) as m,if(sum(a.amt) is null,0,sum(a.amt)) as amt from v1 as a join tmp b where year(orderdate)=year(b.es) and month(orderdate)=month(b.es) and b.es<=$en ) select * from tmp; end $$ delimiter ; call p2('2018-1-1','2018-3-1',(select customerid from customers where companyname='香格利食品有限公司'));哪里错了
时间: 2024-02-12 21:08:01 浏览: 144
您的存储过程中有一些问题,具体如下:
1. 在 `set @sql` 语句中,日期变量 `$start` 和 `$en` 需要用单引号括起来,即 `'{$start}'` 和 `'{$en}'`。
2. 在 `if(day($start)>day($en))` 语句中,变量 `$start` 应该改为 `@start`,因为这是一个 MySQL 变量,而不是存储过程的输入参数。
3. 在 `with recursive tmp as(...)` 语句中,您需要使用 `select` 语句从 `v1` 视图中选择数据,而不是从 `orderitems` 和 `orders` 表中选择数据。因此,您需要将 `from orderitems a join orders b using(Orderid)` 改为 `from v1`。
下面是修改后的存储过程:
```
drop procedure if exists p2;
delimiter $$
create procedure p2(start_date date, end_date date, cusid varchar(20))
begin
set @sql=concat('create or replace view v1 as select orderdate,sum(amount) as amt from orderitems a join orders b using(Orderid) where orderdate between ''',start_date,''' and ''',end_date,''' and customerid="',cusid,'" group by orderdate');
prepare stmt from @sql;
execute stmt;
if(day(start_date)>day(end_date)) then
set start_date=concat(year(start_date),month(start_date),day(end_date));
end if;
with recursive tmp as (
select start_date as ls,
timestampadd(month,1,start_date) as es,
year(start_date) as y,
month(start_date) as m,
if(sum(amt) is null, 0, sum(amt)) as amt
from v1
where year(orderdate)=year(start_date) and month(orderdate)=month(start_date)
union all
select b.es as ls,
timestampadd(month,1,b.es) as es,
year(timestampadd(month,1,b.es)) as y,
month(timestampadd(month,1,b.es)) as m,
if(sum(a.amt) is null, 0, sum(a.amt)) as amt
from v1 as a
join tmp b
where year(orderdate)=year(b.es) and month(orderdate)=month(b.es) and b.es<=end_date
)
select * from tmp;
end$$
delimiter ;
call p2('2018-1-1', '2018-3-1', (select customerid from customers where companyname='香格利食品有限公司'));
```
希望能帮助到您!
阅读全文