强制SQL始终通过R从视图返回至少一行。

huangapple go评论72阅读模式
英文:

Force SQL to always return at least one row from view, through R

问题

在我的机构中,我们经常使用R来查询SQL数据库并返回数据框。

以下是代码示例:

df <- dbGetQuery(jdbcConnection, 
               "select * from companydatabase.specificview") 

问题是,有一个视图经常是空的。也就是说,它存在,SQL开发工具中可见列:

强制SQL始终通过R从视图返回至少一行。

但通常它是空的,没有任何行。因此,如果我尝试查询它,就会出错。

强制SQL始终通过R从视图返回至少一行。

因此,在解决如何防止R在发生这种情况时出错时,我有两种可能的方法:

  1. 使用trycatch()来处理错误并继续执行(我也会这样做)

  2. 确保它始终返回至少一行,无论如何。

我如何做到这一点(#2)?我如何确保我总是得到至少一行空行而不导致SQL错误?

英文:

At my institution we often use R to query SQL databases and return data frames.

The code will look like this:

df&lt;-dbGetQuery(jdbcConnection, 
               &quot;select * from companydatabase.specificview&quot;) 

The problem is, there's one view that's often empty. I.e. it exists, there are columns visible in SQL developer:

强制SQL始终通过R从视图返回至少一行。

but often it's empty with zero rows. And so if I try to query it, I get an error.

强制SQL始终通过R从视图返回至少一行。

So when figuring out how to prevent R from getting error when that happens, I have two possible avenues:

  1. use trycatch() to handle errors and move past it (which I'm also going to do)

  2. make sure it always brings back at least one row, no matter what.

How do I do that (#2)? How do I just make sure I always get at least one blank row and the SQL doesn't error?

答案1

得分: 0

你可以修改视图并添加一个 union all 子句来添加一行虚拟数据。这将确保每次都会获取至少一行数据。

你的新视图将如下所示 -

create or replace view specificview as
<<现有的选择子句>>
union all
select 'dummy' as key, null as col1, null as col2... from dual
英文:

you can alter the view and add a union all clause to add a dummy row. This will ensure you will get at least 1 row every time.

Your new view will look like this -

create or replace view specificview as
&lt;&lt;existing select clause&gt;&gt;
union all
select &#39;dummy&#39; as key, null as col1, null as col2... from dual

</details>



huangapple
  • 本文由 发表于 2023年5月31日 22:58:49
  • 转载请务必保留本文链接:https://go.coder-hub.com/76374855.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定