使用DBI从光标返回值进行循环计算
我试图了解如何从涉及使用DBI循环的光标的SQL查询中返回计算值。例如,我使用加载到Oracle数据库(V19C)的 mtcars 数据集。看起来像这样:
head(DBI::dbGetQuery(con, "SELECT * FROM TEST.MTCARS"))
# MANUFACTURER MPG CYL DISP HP DRAT WT QSEC VS AM GEAR CARB
# 1 Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
# 2 Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
# 3 Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
# 4 Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
# 5 Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
# 6 Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
现在,例如,我想迭代的总和mpg。我意识到我可以简单地使用sum
函数而不是循环,但是在这里,求和过程是另一个函数的占位符,因此为了一个简单的示例而幽默我!
在下面,我声明我的运行总数bar
,然后在mtcars表的MPG列上循环,将每个mpg值添加到运行总计中。循环结束后,我有一个我想返回的总数,但是我不知道该怎么做。 返回
似乎仅返回整数,因此在这里没有真正的意义。
tmp <- DBI::dbGetQuery(con,
"DECLARE
bar NUMBER:=0;
BEGIN
FOR foo IN (SELECT MPG FROM TEST.MTCARS)
LOOP
bar := bar + foo.MPG;
END LOOP;
DBMS_OUTPUT.PUT_LINE(bar);
END;")
tmp
#[1] TRUE
我应该如何从上面的计算中返回值?在此示例中,我希望获得值642.9,但我实现了。
I'm trying to understand how to return a calculated value from a SQL query that involves a cursor FOR LOOP using DBI. As an example, I use the mtcars dataset loaded into an Oracle database (v19c). It looks like this:
head(DBI::dbGetQuery(con, "SELECT * FROM TEST.MTCARS"))
# MANUFACTURER MPG CYL DISP HP DRAT WT QSEC VS AM GEAR CARB
# 1 Mazda RX4 21.0 6 160 110 3.90 2.620 16.46 0 1 4 4
# 2 Mazda RX4 Wag 21.0 6 160 110 3.90 2.875 17.02 0 1 4 4
# 3 Datsun 710 22.8 4 108 93 3.85 2.320 18.61 1 1 4 1
# 4 Hornet 4 Drive 21.4 6 258 110 3.08 3.215 19.44 1 0 3 1
# 5 Hornet Sportabout 18.7 8 360 175 3.15 3.440 17.02 0 0 3 2
# 6 Valiant 18.1 6 225 105 2.76 3.460 20.22 1 0 3 1
Now, as an example, let's say I want to iteratively sum MPG. I realise that I could simply use the SUM
function instead of a loop, but here the summing process is a placeholder for another function so humour me for the sake of a simple example!
Below, I declare my running total variable bar
and then loop over the MPG column of the MTCARS table adding each MPG value to the running total. When the loop finishes, I have a total that I'd like to return, but I can't figure out how to do so. RETURN
seems to only return integers, so doesn't really make sense here.
tmp <- DBI::dbGetQuery(con,
"DECLARE
bar NUMBER:=0;
BEGIN
FOR foo IN (SELECT MPG FROM TEST.MTCARS)
LOOP
bar := bar + foo.MPG;
END LOOP;
DBMS_OUTPUT.PUT_LINE(bar);
END;")
tmp
#[1] TRUE
How should I return a value from a calculation like the one above? For this example, I would expect to get the value 642.9, but I get TRUE.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
就像我在评论中说的那样,这是一种方法(我的示例是在Scott@hr上):
或
Like I said in comment this is one way to do it (my example is on scott@hr):
OR