SQL type of DATE are being returned as characters in my results. I cannot cast anything to DATE. Here is a reprex.
con <- dbConnect(odbc(),
Driver = "SQL Server",
Server = "*****"
Database = "******",
user = "******",
password = "****",
Port = ****)
# Create Test table
dbSendStatement(con, "CREATE table dbo.my_table
(zipcode int, myDate date, myDateTime datetime, animal varchar(20));")
#Create Test Data
dbSendStatement(con,"insert into my_table (zipcode, myDate, myDateTime, animal)
values (90210, '2010-01-01', GETDATE(), 'cat')")
tbl(con, "my_table") %>%
mutate(castDateFail = as.Date(myDate)) %>%
mutate(newDateFail = as.Date("1969-07-29"))
zipcode myDate myDateTime animal castDateFail newDateFail
<int> <chr> <dttm> <chr> <chr> <chr>
1 90210 2010-01-01 2023-06-01 10:06:35 cat 2010-01-01 1969-07-29
- Zipcode returns correctly as an int.
- myDateTime returns correctly as a dttm.
- Why does myDate come back as chr ?
- Why does the cast of myDate fail?
- Why is newDateFail a chr instead of date?
If I pipe to show_query() I get:
SELECT *, TRY_CAST('1969-07-29' AS DATE) AS "newDateFail"
FROM (
SELECT *, TRY_CAST("myDate" AS DATE) AS "castDateFail"
FROM "my_table"
) "q01"
If I collect() the data first, I am able to cast and mutate as expected, but I need to make date comparisons and join with another table before collecting.
I am running:
- R version 4.1.0
- dbplyr_2.3.2
- DBI_1.1.3
- sql Server 15