I am trying to figure out how to extract data from a SQL Server table and save the contents of one table, into separate CSV files, based on a field called ASOFDATE. My ASOFDATE is a month end date.
Here is what I have so far.
library(RODBC)
# connect to database
dbhandle = odbcDriverConnect('driver={SQL Server};server=SERVER_NAME;database=DATABASE_NAME;trusted_connection=true')
sampledata <- sqlQuery(dbhandle, "select * from [SERVER].[dbo].[TABLE]")
# Close the connection
close(dbhandle)
# Create a Date vector containing the 1st of all the subsequent months and subtract 1 day
# date.end.month <- seq(as.Date("2012-02-01"),length=4,by="months")-1
ASOFDATE <- seq(as.Date("2016-02-01"),length=12,by="months")-1
Somehow in here I think I need to loop through the DataFrame, but I’m not sure how to do it.
for (i in sampledata) {
do some kind of filter by ASAOFDATE
write.csv(sampledata, paste0("C:/Users/RSMITH/Desktop/test/", ASOFDATE, ".csv"), row.names = FALSE)
}
So, for instance, I use this to fetch data from the table.
dataset <- sqlFetch(dbhandle, "DATA")
The data set has these fields: N_ID,SEQ_NO,REPORT_PERIOD_END,CONTACT_ID,CONSOL_KEY,CUSTOMER_NAME,COMPANY_CODE,SECTOR,OFFICER,ASOFDATE,COMPANY,REPORT_LINE
I create a list of month end dates that I want to 'filter' for: ASOFDATE <- seq(as.Date("2016-02-01"),length=12,by="months")-1
Then, 'filter' records in the table, based on ASOFDATE, and save each chunk as a CSV, with the date in the file name.
I'm 100% sure this is possible, but I just don't know how to cut up the data into chunks and save each chunk.