Question

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 function, brackets and it doesn't want to work.

Here is the code:

    dbquery <- sqlQuery(dbhandle, 'SELECT ST03001, ST03003, ST03007, ST03015, ST03012, ST03020, ST03021, ST03022 
    FROM deh_10.dbo.ST031000 ST031000 
    WHERE (ST03015>'2013-01-01')')

I usually get this error message:

    "dbquery <- sqlQuery(dbhandle, 'SELECT ST03001, ST03003, ST03007, ST03015, ST03012,
     ST03020, ST03021, ST03022 FROM deh_10.dbo.ST031000 ST031000 WHERE
     (ST03015>DATE('2013"

After the date filter I have several other filters separated from each other by OR (excluded from the example).

Was it helpful?

Solution

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 >15826

You 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'))

     ST03001 ST03003 ST03007    ST03015 ST03012 ST03020 ST03021 ST03022
1      73      74      58 2013-05-01      82      85      88      58
2       8      63      71 2013-06-01      37      76      15      44
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top