Rodbc Date Filter
I have been trying to set a query to a MS SQL database through RODBC. Unfortunately I cannot set appropriate date filters. I tried typing date in quotes and single quotes, DATE fun
Solution 1:
It is better to construct your sql query, using paste, specially when you deal with dates. here I convert the dates to numeric, but it is optionally( it depends with the data base, I think that MS SQL convert character to dates automatically). I create my query using paste and sep ='\n':
For example :
query <- paste(
'SELECT ST03001, ST03003, ST03007, ST03015, ST03012, ST03020, ST03021, ST03022 ',
'FROM ST031000',
paste("WHERE ST03015 >" , as.numeric(as.Date('2013-05-01')),sep=''),
sep='\n')
Then using cat:
cat(query)
SELECT ST03001, ST03003, ST03007, ST03015, ST03012, ST03020, ST03021, ST03022
FROM ST031000
WHERE ST03015 >15826You can also do this (no need to convert to a numeric)
query <- paste(
+ 'SELECT ST03001, ST03003, ST03007, ST03015, ST03012, ST03020, ST03021, ST03022 ',
+ 'FROM ST031000',
+ paste("WHERE ST03015 >'" , as.Date('2013-05-01'),"'",sep=''),
+ sep='\n')
> cat(query)
SELECT ST03001, ST03003, ST03007, ST03015, ST03012, ST03020, ST03021, ST03022
FROM ST031000
WHERE ST03015 >'2013-05-01'Here an example using sqldf package. I create some data:
values <- as.data.frame(matrix(sample(1:100,8*6*3,rep=T),ncol=8))
colnames(values) <- c('ST03001', 'ST03003', 'ST03007', 'ST03015', 'ST03012', 'ST03020', 'ST03021', 'ST03022')
values$ST03015 = seq(as.Date("2012/1/1"), as.Date("2013/06/1"), length.out= nrow(values))
Then:
sqldf(query <- paste(
'SELECT ST03001, ST03003, ST03007, ST03015, ST03012, ST03020, ST03021, ST03022 ',
'FROM ST031000',
paste("WHERE ST03015 >" , as.numeric(as.Date('2013-05-01')),sep=''),
sep='\n'))
ST03001ST03003ST03007ST03015ST03012ST03020ST03021ST0302217374582013-05-01828588582863712013-06-0137761544
Post a Comment for "Rodbc Date Filter"