RODBC sqlSave table creation problems
Asked Answered
F

6

10

I'm having trouble creating a table using RODBC's sqlSave (or, more accurately, writing data to the created table).

This is different than the existing sqlSave question/answers, as

  1. the problems they were experiencing were different, I can create tables whereas they could not and
  2. I've already unsuccesfully incorporated their solutions, such as closing and reopening the connection before running sqlSave, also
  3. The error message is different, with the only exception being a post that was different in the above 2 ways

I'm using MS SQL Server 2008 and 64-bit R on a Windows RDP.

I have a simple data frame with only 1 column full of 3, 4, or 5-digit integers.

> head(df)
                        colname
1                           564
2                          4336
3                         24810
4                         26206
5                         26433
6                         26553

When I try to use sqlSave, no data is written to the table. Additionally, an error message makes it sound like the table can't be created though the table does in fact get created with 0 rows.

Based on a suggestion I found, I've tried closing and re-opening the RODBC connection right before running sqlSave. Even though I use append = TRUE, I've tried dropping the table before doing this but it doesn't affect anything.

> sqlSave(db3, df, table = "[Jason].[dbo].[df]", append = TRUE, rownames = FALSE)
Error in sqlSave(db3, df, table = "[Jason].[dbo].[df]",  : 
  42S01 2714 [Microsoft][ODBC SQL Server Driver][SQL Server]There is already 
an object named 'df' in the database.
[RODBC] ERROR: Could not SQLExecDirect 'CREATE TABLE [Jason].[dbo].[df]  
("df" int)'

I've also tried using sqlUpdate() on the table once it's been created. It doesn't matter if I create it in R or SQL Server Management Studio, I get the error table not found on channel

Finally, note that I have also tried this without append = TRUE and when creating a new table, as well as with and without the rownames option.

Mr.Flick from Freenode's #R had me check if I could read in the empty table using sqlQuery and indeed, I can.

Update

I've gotten a bit closer with the following steps:

  1. I created an ODBC connection that goes directly to my Database within the SQL Server, instead of just to the default (Master) DB then specifying the path to the table within the table = or tablename = statements
  2. Created the table in SQL Server Management Studio as follows

GO

CREATE TABLE [dbo].[testing123]( [Person_DIMKey] [int] NULL ) ON [PRIMARY]

GO

  1. In R I used sqlUpdate with my new ODBC connection and no brackets around the tablename

  2. Now sqlUpdate() sees the table, however it complains that it needs a unique column

  3. Indicating that the only column in the table is the unique column with index = colname results in an error saying that the column does not exist

  4. I dropped and recreated the table specifying a primary key,

GO

CREATE TABLE [dbo].[jive_BNR_Person_DIMKey]( [jive_BNR_Person_DIMKey] [int] NOT NULL PRIMARY KEY ) ON [PRIMARY]

GO

which generated both a Primary Key and Index (according to the GUI interface of SQL Sever Management Studio) named PK__jive_BNR__2754EC2E30F848ED

  1. I specified this index/key as the unique column in sqlUpdate() but I get the following error:

Error in sqlUpdate(db4, jive_BNR_Person_DIMKey, tablename = "jive_BNR_Person_DIMKey", : index column(s) PK__jive_BNR__2754EC2E30F848ED not in database table

For the record, I was specifying the correct column name (not "colname") for index; thanks to MrFlick for requesting clarification.

Also, these steps are numbered 1 through 7 in my post but StackOverflow resets the numbering of the list a few times when it gets displayed. If anyone can help me clean that aspect of this post up I'd appreciate it.

Firth answered 28/5, 2014 at 13:53 Comment(4)
I reopened this because I think @Andrie might have been a little hasty. The potential duplicate doesn't have any clear answer, and you appear to have already tried the main suggestion there anyway.Febri
Be aware, though, that these sorts of issues can be hard for people without access to your db to help with. (At least for R folks who may or may not be db experts.) One possibility is that R is attempting to append, but somehow the table structure doesn't match your data frame well enough, so it is attempting to create a new one and failing because a table by that name exists.Febri
Fair enough. I have also tried it without append = TRUE and creating a new table, I had the same problem.Firth
Thanks, @Febri I'm still not used to these new super-powers. I wanted to flag the duplicate, not kill the question completely.Zippy
F
10

After re-reading the RODBC vignette, here's the simple solution that worked:

sqlDrop(db, "df", errors = FALSE)
sqlSave(db, df)

Done.

After experimenting with this a lot more for several days, it seems that the problems stemmed from the use of the additional options, particularlly table = or, equivalently, tablename =. Those should be valid options but somehow they manage to cause problems with my particular version of RStudio ((Windows, 64 bit, desktop version, current build), R (Windows, 64 bit, v3), and/or MS SQL Server 2008.

sqlSave(db, df) will also work without sqlDrop(db, "df") if the table has never existed, but as a best practice I'm writing try(sqlDrop(db, "df", errors = FALSE), silent = TRUE) before all sqlSave statements in my code.

Firth answered 2/6, 2014 at 18:33 Comment(0)
A
10

After hours of working on this, I was finally able to get sqlSave to work while specifying the table name--deep breathe, where to start. Here is the list of things I did to get this to work:

  • Open 32-bit ODBC Administrator and create a User DSN and configure it for your specific database. In my case, I am creating a global temp table so I linked to tempdb. Use this connection Name in your odbcConnection(Name). Here is my code myconn2 <- odbcConnect("SYSTEMDB").
  • Then I defined my data types with the following code: columnTypes <- list(Record = "VARCHAR(10)", Case_Number = "VARCHAR(15)", Claim_Type = "VARCHAR(15)", Block_Date = "datetime", Claim_Processed_Date = "datetime", Status ="VARCHAR(100)").
  • I then updated my data frame class types using as.character and as.Date to match the data types listed above.
  • I already created the table since I've been working on it for hours so I had to drop the table using sqlDrop(myconn2, "##R_Claims_Data").
  • I then ran: sqlSave(myconn2, MainClmDF2, tablename = "##R_Claims_Data", verbose=TRUE, rownames= FALSE, varTypes=columnTypes)

Then my head fell off because it worked! I really hope this helps someone going forward. Here are the links that helped me get to this point:

Table not found

sqlSave in R

RODBC

Ardisardisj answered 12/10, 2016 at 16:37 Comment(1)
Thanks. Brutal that this is necessary!Upbeat
U
2

We have had this same problem, which after a bit of testing we solved simply by not using square brackets in the schema and table name reference.

i.e. rather than writing

table = "[Jason].[dbo].[df]"

instead write

table = "Jason.dbo.df"

Appreciate this is now long past the original question, but just for anyone else who subsequently trips up on this problem, this is how we solved it. For reference, we found this out by writing a simple 1 item dataframe to a new table, which when inspected in SQL contained the square brackets in the table name.

Unbuild answered 20/6, 2017 at 10:5 Comment(0)
N
2

Here are a few rules of thumb:

  1. If things aren't working out, then manually specify the column types just as @d84_n1nj4 suggested.

columnTypes <- list(Record = "VARCHAR(10)", Case_Number = "VARCHAR(15)", Claim_Type = "VARCHAR(15)", Block_Date = "datetime", Claim_Processed_Date = "datetime", Status ="VARCHAR(100)")

sqlSave(myconn2, MainClmDF2, tablename = "##R_Claims_Data", verbose=TRUE, rownames= FALSE, varTypes=columnTypes)

  1. If #1 doesn't work, then continue to specify the columns, but specify them all as VARCHAR(255). Treat this as a temp or staging table, and move the data over with sqlQuery with your next step, just as @danas.zuokas suggested. This should work, but even if it doesn't, it gets you closer to the metal and puts you in better position to debug the problem with SQL Server Profiler if you need it. <- And yes, if you still have a problem, it's likely due to either a parsing error or type conversion.

columnTypes <- list(Record = "VARCHAR(255)", Case_Number = "VARCHAR(255)", Claim_Type = "VARCHAR(255)", Block_Date = "VARCHAR(255)", Claim_Processed_Date = "VARCHAR(255)", Status ="VARCHAR(255)")

sqlSave(myconn2, MainClmDF2, tablename = "##R_Claims_Data", verbose=TRUE, rownames= FALSE, varTypes=columnTypes)

sqlQuery(channel, 'insert into real_table select * from R_Claims_Data')

  1. Due to RODBC's implementation, and not due to any inherent limitation in T-SQL, R's logical type (i.e. [TRUE, FALSE]) will not convert to T-SQL's BIT type (i.e. [1, 0]), so don't try this. Either convert the logical type to [1, 0] in the R layer or take it down to the SQL layer as a VARCHAR(5) and convert it to a BIT in the SQL layer.
Norward answered 18/1, 2018 at 13:2 Comment(2)
I did all of the above steps but didn't work for me since I had brackets for the table name. Here is the same [comment] (https://mcmap.net/q/1176695/-why-won-39-t-rodbc-upload-a-dataframe-to-sql-server).Austinaustina
thanks @Jim, #2 worked for me. I was struggling so long and finally settled up now.Undersea
I
1

In addition to some of the answered posted earlier, here's my workaround. NOTE: I use this as part of a small ETL process, and the destination table in the DB is dropped and recreated each time.

Basically you want to name your dataframe what you destination table is named:

RodbcTest <- read.xlsx('test.xlsx', sheet = 4, startRow = 1, colNames = TRUE, skipEmptyRows = TRUE)

Then make sure your connection string includes the target database (not just server):

conn <- odbcDriverConnect(paste("DRIVER={SQL Server};Server=localhost\\sqlexpress;Database=Charter;Trusted_Connection=TRUE"))

after that, I run a simple sqlQuery that conditionally drops the table if it exists:

sqlQuery(conn, "IF OBJECT_ID('Charter.dbo.RodbcTest') IS NOT NULL DROP TABLE Charter.dbo.RodbcTest;")

Then finally, run sqlSave without the tablename param, which will create the table and populate it with your dataframe:

sqlSave(conn, RodbcTest, safer = FALSE, fast = TRUE)
Innovate answered 20/1, 2016 at 5:45 Comment(0)
K
0

I've encountered the same problem-- the way I found around it is to create the an empty table using regular CREATE TABLE SQL syntax, and then append to it via sqlSave. For some reason, when I tried it your way, I could actually see the table name in the MSSQL database - even after R threw the error message you showed above - but it would be empty.

Knucklehead answered 28/5, 2014 at 17:8 Comment(4)
Unfortunately, it still gives me the error message: 2S01 2714 [Microsoft][ODBC SQL Server Driver][SQL Server]There is already an object named 'df' in the database. Ironically, if I try it with a non-existing table name it says: Error in sqlColumns(channel, tablename) : ‘[Jason].[dbo].[df2]’: table not found on channelFirth
Yep, sqlSave will create the object, but it will be empty. What you'll need to do is to drop df in regular syntax, then remake the table in regular syntax, and then append to it in sqlSaveKnucklehead
I created it in SQL Server Management Studio with the statement "CREATE TABLE somenewtable (BNR_Person_DIMKey int);" then in R ran the sqlSave with append = TRUE on this new table and got that error. The table I created in SQL outside of R had never existed in R (meaning I never tried to sqlSave using that table name until I first did CREATE TABLE in SQL Server Management Studio). I just tried it again after your comment to confirm. If you have any other variation to try then I am available to try it immediately.Firth
Argh. Bummer -- I didn't have that issue.Knucklehead

© 2022 - 2024 — McMap. All rights reserved.