Skip to content

Instantly share code, notes, and snippets.

@DavidPatShuiFong
Created January 26, 2021 00:16
Show Gist options
  • Select an option

  • Save DavidPatShuiFong/7b47a9804a497b605e477f1bf6c38b37 to your computer and use it in GitHub Desktop.

Select an option

Save DavidPatShuiFong/7b47a9804a497b605e477f1bf6c38b37 to your computer and use it in GitHub Desktop.
Test MSSQL casting from (invalid) character to integer/numeric.
library(dbplyr)
library(dplyr, warn.conflicts = FALSE)
df <- data.frame(x = c("1.3", "2x"))
# both a 'float' (non-integer) and an 'invalid' number in the column
con <- DBI::dbConnect(...) # connection to a MSSQL database
db <- copy_to(con, df, "##test")
db %>% mutate(
float = TRY_CAST(x %as% sql("FLOAT")),
integer = TRY_CAST(x %as% sql("INTEGER")),
bigint = TRY_CAST(x %as% sql("BIGINT")),
numeric = TRY_CAST(x %as% sql("NUMERIC")),
doublecast_integer = TRY_CAST(TRY_CAST(x %as% sql("NUMERIC")) %as% sql("INTEGER")),
doublecast_bigint = TRY_CAST(TRY_CAST(x %as% sql("NUMERIC(38,0)")) %as% sql("BIGINT"))
)
@DavidPatShuiFong
Copy link
Author

modified version of Gist as originally written by Hadley Wickham. For testing purposes of dbplyr in the tidyverse (tidyverse/dbplyr#555)

@hadley
Copy link

hadley commented Jan 26, 2021

Can you please include the results too?

@DavidPatShuiFong
Copy link
Author

DavidPatShuiFong commented Jan 27, 2021

R version 4.0.3 on openSuSE Linux. Microsoft SQL Server version 15.00.4043 (2019), on openSuSE Linux.

Results of above gist :

# Source:   lazy query [?? x 7]
# Database: Microsoft SQL Server 15.00.4043[dbo@localhost/master]
  x     float integer  bigint numeric doublecast_integer doublecast_bigint
  <chr> <dbl>   <int> <int64>   <dbl>              <int>           <int64>
1 1.3     1.3      NA      NA       1                  1                 1
2 2x     NA        NA      NA      NA                 NA                NA

TRY_CAST to INTEGER or BIGINT returns NULL/NA for entire column if invalid number (in this case, with an 'x') in a single row and a non-integer value in another row. Normally, the non-integer value can be successfully cast to integer.

@DavidPatShuiFong
Copy link
Author

R version 3.5.3 on Windows 10. Microsoft SQL Server 12.00.2000 (2014), on Windows 10.

Results of above gist:

# Source:   lazy query [?? x 7]
# Database: Microsoft SQL Server 12.00.2000[bpsrawdata@DESKTOP-BH8LGMO\BPSINSTANCE/bpssamples]
  x     float integer bigint  numeric doublecast_integer doublecast_bigint
  <chr> <dbl>   <int> <int64>   <dbl>              <int> <int64>          
1 1.3     1.3      NA NA            1                  1  1               
2 2x     NA        NA NA           NA                 NA NA      

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment