-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathsession-sql.qmd
118 lines (85 loc) · 2.5 KB
/
session-sql.qmd
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
---
title: "Introduction to R and Rstudio"
subtitle: "Session - SQL connections"
---
## SQL connections
- A great number of data sources are via SQL servers
::: incremental
- R and SQL process in different architecture (SQL is often more powerful depending on the computer processing speed)
- Packages are available to either use whole SQL scripts or use R functions to process data in the SQL environment
:::
## Connection packages
Firstly the connection needs to be set up using 2 libraries:
```{r}
library(DBI)
library(odbc)
```
!!! **These have not been pre-loaded to the Posit Cloud to prevent connection to an insecure area** !!!
## Connection string
Three areas are specific to the user and database
```{r}
#| code-line-numbers: "4|5|6"
con_udal <- DBI::dbConnect(
drv = odbc::odbc(),
driver = "ODBC Driver 17 for SQL Server",
server = serv,
database = db,
UID = user,
authentication = "ActiveDirectoryInteractive"
)
```
:::notes
Debatable how much needs to be hidden as this is authenticated by the Active Directory but for reference.
:::
## Save important credentials
The {usethis} package has many useful functions including:
```{r}
library(usethis)
usethis::edit_r_environ()
```
## Amending .Renviron
::: columns
::: {.column width="60%"}
1. Copy the following directly to `.Renviron` with no spaces
1. Amend to your specific details in the quotes
1. Save the `.Renviron` file `Ctrl+S` and Restart RStudio using `Ctrl+Shift+F10` or `Session/Restart R`
:::
::: {.column width="40%"}
```{r}
server="server_name"
db="db_name"
user="[email protected]"
```
:::
:::
## Connect in the Quarto document
1. Create a new R chunk with <img src="img/icons/notebook-insert-chunk.png" alt="A picture of the green square with c button from RStudio to create a new chunk"/> or using `Ctrl+Alt+i`
1. Copy the code below
1. Run the code chunk using the green arrow in top right
```{r connection}
con_udal <- DBI::dbConnect(
drv = odbc::odbc(),
driver = "ODBC Driver 17 for SQL Server",
server = serv,
database = db,
UID = user,
authentication = "ActiveDirectoryInteractive"
)
```
## SQL code in R
A single SQL script can be run within R.
Each temporary table needs its own script or combine in a CTE (common table expression).
```{r}
df_one <- dbGetQuery(
conn = con_udal,
statement = "
SELECT appointment_date,
appointment_status,
HCP_Type,
Count_Of_Appointments
FROM Schema_Name.Table_Name
WHERE Appointment_Date >= '2022-11-25'
"
)
```
## End session