如何在SQL Server非标准架构表上使用dplyr tbl [英] How to use dplyr tbl on a SQL Server non-standard schema table
问题描述
我的问题是如何在不使用SQL Server的表上使用 dplyr
函数,例如 tbl
使用默认的 dbo模式?
My question is how can I use dplyr
functions, such as tbl
, on SQL Server tables that do not use the default "dbo" schema?
有关更多上下文,我试图将此处给出的R数据库示例应用于我自己的表:
https://db.rstudio.com/ (向下滚动至标题为快速示例的部分)。
For more context, I am trying to apply the R database example given here to my own tables: https://db.rstudio.com/ (scroll down to the section entitle "Quick Example").
开始就可以了。第一部分运行良好:
It starts out ok. This first section runs fine:
install.packages("dplyr")
install.packages("odbc")
install.packages("dbplyr")
install.packages("DBI")
con <- DBI::dbConnect(odbc::odbc(),
Driver = "SQL Server",
Server = [My Server Name],
Database = "mydatabase",
UID = [My User ID],
PWD = [My Password],
Port = 1433)
我能够连接到SQL Server并加载到数据库中的表中。我知道这是因为
I am able to connect to my SQL Server and load in the tables in my database. I know this because
DBI :: dbListTables(con)
返回可用表的名称(但不包含任何模式)。
returns the names of my available tables (but without any schema).
当应用于我自己的一个表时,示例代码的下一行也可以使用,返回表中列的名称。
The next line of example code also works when applied to one of my own tables, returning the names of the columns in the table.
DBI :: dbListFields(con, mytable1)
但是,一旦我尝试运行下一行:
However, once I try to run the next line:
dplyr :: tbl(con, mytable1)
我收到无效的对象名'mytable1'
错误,而不是预期的表预览为在示例中。
I get an Invalid object name 'mytable1'
error, rather than the expected table preview as in the example.
当我在不同的表mytable2上运行相同的代码时,不会发生此错误。这次,正如预期的那样,我在运行时得到了mytable2的预览:
This error does not arise when I run the same code on a different table, mytable2. This time, as expected, I get a preview of mytable2 when I run:
dplyr :: tbl(con, mytable2)
mytable1和mytable2之间的区别是架构。 mytable1使用虚构的 abc架构,即 mydatabase.abc.mytable1 。 mytable2使用默认的 dbo模式,即 mydatabase.dbo.mytable2 。
One difference between mytable1 and mytable2 is the schema. mytable1 uses a made-up "abc" schema i.e. mydatabase.abc.mytable1. mytable2 uses the default "dbo" schema i.e. mydatabase.dbo.mytable2.
我尝试了 dplyr :: tbl( con, abc.mytable1)
,但出现相同的 Invalid object name
错误。同样地,当我尝试 dplyr :: tbl(con, dbo.mytable2)
时(尽管当我排除 dbo $ c时运行良好$ c>部分)。
I tried dplyr::tbl(con, "abc.mytable1")
but I get the same Invalid object name
error. Likewise when I tried dplyr::tbl(con, "dbo.mytable2")
(although it runs fine when I exclude the dbo
part).
那么我该如何使用 dplyr
函数,例如 tbl
,在不使用默认 dbo架构的SQL Server表上?谢谢。
So how can I use dplyr
functions, such as tbl
, on SQL Server tables that do not use the default "dbo" schema? Thanks.
推荐答案
您可以使用 dbplyr :: in_schema
。
You can use dbplyr::in_schema
.
在您的情况下:
dplyr::tbl(con, dbplyr::in_schema("abc", "mytable1"))
这篇关于如何在SQL Server非标准架构表上使用dplyr tbl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!