Sql 通过一个简单的示例学习在Firebird中使用执行块
我还没有在Firebird中使用过execute block,但我正在努力学习如何使用它 我试图从一个简单的例子中学习,然后将扩展到更复杂的情况 假设我有两个表,如下所示:Sql 通过一个简单的示例学习在Firebird中使用执行块,sql,firebird,execute,Sql,Firebird,Execute,我还没有在Firebird中使用过execute block,但我正在努力学习如何使用它 我试图从一个简单的例子中学习,然后将扩展到更复杂的情况 假设我有两个表,如下所示: +------------+------+ | Clientcode | name | +------------+------+ | 123 | A | | 234 | B | +------------+------+ 我有以下代码 execute block returns (
+------------+------+
| Clientcode | name |
+------------+------+
| 123 | A |
| 234 | B |
+------------+------+
我有以下代码
execute block returns (client integer,amount double)
as
declare variable client_code integer;
begin
for
select clientcode from clients
into : client_code
do
begin
select :client_code,sum(value) from orders group by 1
into :client, :order_id;
end
end
基本上,我想让客户机表中的每个客户机计算orders表中订单的总和。我知道在这种情况下不需要执行块,但通过一个简单的示例,我可能能够更好地理解它
+-------------+--------+
| client_code | amount |
+-------------+--------+
| 123 | 30 |
| 234 | 10 |
+-------------+--------+
正确的语法是什么?代码中缺少一些东西:
订单
中选择时,您需要一个where
-子句,以将其仅限于当前客户端的行amount
,而不是不存在的变量order\u id
client
达到相同目的时,您不需要变量client\u code
decimal(18,2)
而不是double-precision
,对于货币值,使用精确精度的数字类型,如decimal
是更好的选择):
这相当于以下查询:
select clients.clientcode as client_code, sum(orders.amount) as amount
from clients
left join orders on clients.clientcode = orders.clientcode
group by clients.clientcode
另见此
请记住,基本上是一个未存储的Firebird存储过程。带有
suspend
的execute块
表现为a,可以生成零行或多行,而不带suspend
的块表现为a,只能生成一行。Hi Mark,感谢您给出的良好解释。Rgrdsstart,阅读有关存储过程的信息。从本质上讲,EB是一次性的临时匿名SP。存储过程在Interbase/Firebird中存在了几十年,历史上有很多关于它们的信息。在书籍、论坛、常见问题解答中,无处不在。当您轻松使用SPs时,EBs都是一样的,但没有名称,也没有持久性。很简单。你好,谢谢你的建议。我要这个。
execute block returns (client_code integer,amount decimal(18,2))
as
begin
for select clientcode from clients
into client_code
do
begin
select sum(amount) from orders where clientcode = :client_code
into amount;
suspend;
end
end
select clients.clientcode as client_code, sum(orders.amount) as amount
from clients
left join orders on clients.clientcode = orders.clientcode
group by clients.clientcode