Guest User

Untitled

a guest
Jan 15th, 2018
89
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.37 KB | None | 0 0
  1. library(DBI)
  2. library(dplyr)
  3. library(lubridate)
  4.  
  5. # --- Connect to the database via RSQLServer and odbc --------------------------
  6. db <- "your SQL database"
  7. server <- "your SQL server"
  8. conn <- dbConnect(RSQLServer::SQLServer(), server = server, database = db,
  9. properties = list(user = "", password = "",
  10. useNTLMv2 = TRUE, domain = "")
  11. )
  12.  
  13. conn2 <- dbConnect(odbc::odbc(), dsn = "")
  14.  
  15. # --- Create the test table ----------------------------------------------------
  16. dplyr::db_drop_table(conn, "TestTable")
  17.  
  18. if (!dbExistsTable(conn, "TestTable")) {
  19. TestProcessStr <- "
  20. CREATE TABLE TestTable(
  21. Process_ID INT NOT NULL IDENTITY(1,1),
  22. Start_Dt DATE NOT NULL,
  23. End_Dt DATE DEFAULT '9999-12-31',
  24. Comment VARCHAR(30),
  25. PRIMARY KEY( Process_ID )
  26. );"
  27.  
  28. dbExecute(conn, TestProcessStr)
  29. } else {
  30. message("TestTable exists")
  31. }
  32.  
  33. # --- Write to test table using different connections --------------------------
  34.  
  35. rowadd <- data_frame(Start_Dt = Sys.Date(), End_Dt = Sys.Date() + months(3),
  36. Comment = "SQLServer, Date as Date")
  37.  
  38. write_res <- dbWriteTable(conn, name = "TestTable",
  39. value = rowadd, append = T)
  40.  
  41. # Convert all dates to character
  42. rowadd <- rowadd %>% mutate_if(is.Date, as.character) %>%
  43. mutate(Comment = "SQLServer, Date as Char")
  44.  
  45. write_res <- dbWriteTable(conn, name = "TestTable",
  46. value = rowadd, append = T)
  47.  
  48. rowadd <- data_frame(Start_Dt = Sys.Date(), End_Dt = Sys.Date() + months(3)) %>%
  49. mutate(Comment = "ODBC, Date as Date")
  50.  
  51. write_res <- dbWriteTable(conn2, name = "TestTable",
  52. value = rowadd, append = T)
  53.  
  54.  
  55. # Convert all dates to character
  56. rowadd <- rowadd %>% mutate_if(is.Date, as.character) %>%
  57. mutate(Comment = "ODBC, Date as Character")
  58.  
  59. write_res <- dbWriteTable(conn2, name = "TestTable",
  60. value = rowadd, append = T)
  61.  
  62.  
  63. # View database status
  64. ttab <- dbReadTable(conn, "TestTable")
  65. ttab
  66.  
  67. # --- Disconnect ---------------------------------------------------------------
  68.  
  69. dbDisconnect(conn)
  70. dbDisconnect(conn2)
  71.  
  72. Process_ID Start_Dt End_Dt Comment
  73. 1 1 2018-01-14 2018-04-14 SQLServer, Date as Date
  74. 2 2 2018-01-15 2018-04-15 SQLServer, Date as Char
  75. 3 3 2018-01-15 2018-04-15 ODBC, Date as Date
  76. 4 4 2018-01-15 2018-04-15 ODBC, Date as Character
Add Comment
Please, Sign In to add comment