简体   繁体   中英

RODBC issue casting NA's to Float for SQL Server

I'm trying to load a dataframe to a SQL Server 2014 table and am getting:

[Microsoft][SQL Server Native Client 11.0]Invalid character value for cast specification

I'm pretty sure I've narrowed it down to the fact that I'm trying to cast the numeric columns which have NA's to float.

dtype = c(Brand ="nvarchar(100)", Date_Loaded="date", Period="int", col1="float")

sqlSave(con, df, "dbo.test", rownames=FALSE, append=TRUE, verbose=TRUE, varTypes=dtype)

Here is some sample data:

| Brand  | Date_Loaded | Period | col1        |
|--------|-------------|--------|-------------|
| Cereal |   9/18/2015 |    1   |    NA       |
| Cereal |   9/18/2015 |    2   |    NA       |
| Cereal |   9/18/2015 |    3   |    NA       |
| Cereal |   9/18/2015 |    4   |    0.127418 |
| Cereal |   9/18/2015 |    5   |    0.167645 |
| Cereal |   9/18/2015 |    6   |    0.144336 |

I've tried playing with nastring=NULL, NA, '' with no luck. My option now is to just stage it as varchar (which works) and clean it up in SQL but that seems too hacky.

Crappy work around is to just bring everything in as varchar(20) and then put a view on the table that checks for NA and casts to float.

dtype = c(Brand ="nvarchar(100)", Date_Loaded="date", Period="int",col1="varchar(20)")

sqlSave(con, df, "dbo.test", rownames=FALSE, append=TRUE, varTypes=dtype)

create view dbo.test_vw as
SELECT
[Brand]
,[Date_Loaded]
,[Period]
,(case ISNUMERIC(col1) WHEN 1 then cast(col1 as float) else null end) as col1
FROM
dbo.test;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM