我可以在RMarkdown中将系统用户名插入SQL块吗?

时间:2018-01-09 22:00:37

标签: r dplyr r-markdown knitr dbplyr

我正在尝试在knitr SQL chunk中使用创建的变量。我正在尝试使用Sys.getenv("USERNAME")创建变量,因为它用作模式名称的一部分。我目前的代码如下:

```{r}
library(tidyverse)
library(lubridate)
library(dbplyr)
library(DBI)

con <-
DBI::dbConnect(odbc::odbc(), 
  .connection_string = 'driver={SQL Server};
  server=server;
  database=db1;
  trusted_connection=true')

BEGINMONTH <- "01JUN16"
ENDMONTH <- "01JUL16"
```

```{SQL, connection=con}
DROP TABLE [SANDBOX_DB].[ORG\USERNAME].TEMP

SELECT VAR1, VAR2, VAR3
  INTO [SANDBOX_DB].[ORG\USERNAME].TEMP
  FROM [DB1].TABLE
  WHERE DATE BETWEEN ?BEGINMONTH AND ?ENDMONTH
```

我想在第一个块中有一个额外的变量,如下所示:

schema <- paste0("[SANDBOX_DB].[ORG\\", Sys.getenv("USERNAME"), "]")

所以最终的代码看起来像这样:

```{r}
library(tidyverse)
library(lubridate)
library(dbplyr)
library(DBI)

con <-
DBI::dbConnect(odbc::odbc(), 
  .connection_string = 'driver={SQL Server};
  server=server;
  database=db1;
  trusted_connection=true')

BEGINMONTH <- "01JUN16"
ENDMONTH <- "01JUL16"
schema <- paste0("[SANDBOX_DB].[ORG\\", Sys.getenv("USERNAME"), "]")
```

```{SQL, connection=con}
DROP TABLE ?schema.TEMP

SELECT VAR1, VAR2, VAR3
  INTO ?schema.TEMP
  FROM [DB1].TABLE
  WHERE DATE BETWEEN ?BEGINMONTH AND ?ENDMONTH
```

我收到此错误,这似乎与参数输入带引号的SQL块的方式有关。是否有另一种方法可以将用户名更改为SQL块?

Error: <SQL> 'DROP TABLE '[SANDBOX_DB].[ORG\USERNAME]'.TEMP 

SELECT DISTINCT VAR1, VAR2, VAR3
    INTO '[SANDBOX_DB].[ORG\USERNAME]'.TEMP
    FROM [DB1].TABLE
    WHERE DATE BETWEEN '01JUN16' AND '01JUL16'
'
  [Microsoft][ODBC SQL Server Driver][SQL 
Server]Incorrect syntax near '[SANDBOX_DB].[ORG\USERNAME]'. 
Failed to execute SQL chunk

0 个答案:

没有答案