Write to database from R using RODBC:sqlSave not working - sql

I have a SQL database table that I want to populate with data from my R data.frame. The SQL target table ("SQL_table") already exists in the ODBC SQL database, but is empty of data. When I try to write my data, it always errors out. It looks like it's always trying to create the SQL data table?
Here is my code:
con <- odbcConnect("SQL_Database", uid="my_user_name", pwd="my_password")
RODBC::sqlSave(channel=con , dat=my_df, tablename = "SQL_table", append=T)
Here is the error received:
Error in RODBC::sqlSave(channel = con, dat = my_df, :
42S01 2714 [Microsoft][ODBC SQL Server Driver][SQL Server]There is already an object named 'SQL_table' in the database.
[RODBC] ERROR: Could not SQLExecDirect 'CREATE TABLE SQL_table ("rownames" varchar(255) ..."
Troubleshooting thus far:
I tried running it with append=T & append=F. Both ways it tries to create the table, making no difference.
I confirmed that my data schema exactly matches the schema of the target SQL table.
I confirmed that I can write to the SQL database.
I tried dropping the database table, and then have R create it from scratch. Doing so my data will populate then create the table in the SQL database, but not populate it. In other words, it sends the column names and data types, but not the actual data.
Thank you in advance!

Related

dbGetQuery() Error: Can't retrieve the table or table data using SQL in R

I am trying to use the SQL query to count the number of rows of myid in Table_1 data frame. The data frame is already present in R Environment and I retrieved it by following query.
Table_1 <- dbGetQuery(conn, "Select * FROM Patients") .
Now to count() the number of rows of myid in Table_1, I use following query and it says
count_myid <- dbGetQuery(conn, "Select count(myid) FROM Table_1")
Invalid object name 'Table_1'[Microsoft][odbc sql server driver]
[sql server] Statement(s) could not be prepared
Whereas, I checked the above mentioned query for another Table and it works perfectly fine for another table. I spent hours on this to figure out the problem but I couldn't that what is actually wrong in this query and why its not working. I know it can be done using different functions of R. I did used dbReadTable() and all the same queries mentioned in this Question, but not working.
If I try to retrieve it directly from SQL database and not from the R Environment, then it works fine. From SQL DB, I use the following query.
count_myid <- dbGetQuery(conn, "Select count(myid) FROM MyProj.dbo.Patients")

How to create a table from a linked server into the local machine

I need to copy tables from a linked server onto my local machine. I am working in SQL management studio. The linked server is Oracle based. My end goal is to set up a stored proc that deletes a table if it exists and creates a new table in its place with refreshed data. This will be done for many tables as needed. The issue with the below code is that I get the error:
Incorrect syntax near the keyword 'SELECT'.
I am stuck at creating the table.
CREATE TABLE test AS
SELECT DUMMY
FROM OPENQUERY (LServer, '
Select *
from sourceT
');
The data in the dummy table is just one column with a single value "x". I have seen posts that suggest using a certain notation in naming the linked server table, like <server.database.schema.tablename> but this doesn't seem to work,even if I just run the select statement using the openquery. If I just run the select part in the script above, this does work.
CREATE TABLE test AS
Is valid in Oracle but not SQL Server
You want
-- if the table already exists drop it
DROP TABLE IF EXISTS test;
-- now create a table and load into it
SELECT DUMMY
INTO test
FROM OPENQUERY (LServer, '
Select *
from sourceT')

Advantage Server: explore a table in database

Advantage Server 11.0
I use Data Architect and login as ADSSYS.
I create a table
CREATE TABLE bbimp(TEXT NChar(255)) IN DATABASE;
Then I execute second time to be sure the table exists
CREATE TABLE bbimp(TEXT NChar(255)) IN DATABASE;
and get an awaited message
poQuery: Error 7200: AQE Error: State = S0000; NativeError = 2010; [iAnywhere Solutions][Advantage SQL Engine][ISAM]ISAM table already exists
Then I try to know if it exists without the error:
SELECT * from system.tables where name='bbimp';
But result set contains 0 records.
How can I get to know if the table in database exists?
when I execute SQL
select * from bbimp
I get an error:
poQuery: Error 7200: AQE Error: State = HY000; NativeError = 5159; [iAnywhere Solutions][Advantage SQL][ASA] Error 5159: Error encountered when trying to open a database table. The table is a database table. It cannot be opened as a free table. Table name: bbimp
I have a file of the table at
C:\Users\Public\Documents\AgroWinDaten\Daten\bbimp.adt
Selecting from system.tables (in fact all the system. tables) only works for dictionary based connections, not for free connections.
Also you can't query a dictionary based table from a free connection.
If you don't understand the difference, you should look at this question:
What is difference between the Adavanstage Database Sever free table and Advanstage databaseSever Normal table

Creating SQL Connection in Excel that creates and drops temporary tables

I've created query that runs perfectly in Microsoft SQL Server and it utilizes temporary tables it creates and drops. I now want to create a data connection in Microsoft Excel that will run my query and display the results in Excel, so that business partners who do not know SQL can utilize the report.
However, when I try to run the query in a data connection in excel I get errors like the following:
"Database name 'database' ignored, referencing object in tempdb."
OR
"The query did not run, or the database table could not be opened. Check the database server or contact your database administrator. Make sure the external database is available and hasn't been moved or reorganized, then try the operation again."
I then tried to use the phrase "SET NOCOUNT on" before creating my temporary tables but it did not resolve the issue and I still have no report.
Here is how my code is set up
select
x.PRODUCT_ID,
y.SETID,
LW = ISNULL (SUM(y.SALES_QTY) ,0)
INTO database.#tmpLastWeek
--#tempLastWeek is a temporary table I am creating here and inserting values into
from
database.sales_table y
inner join
database.product_table x
on y.PRODUCT_ID = x.PRODUCT_ID
and x.SETID = y.SETID
where
y.stores IN (
'storeslist'
)
and y.sales_week = #this_week - 1
and y.sales_year = #this_year
group by
x.PRODUCT_ID,
y.SETID,
x.DESCR
Then I select from the temporary table #tmpLastWeek
select * from #tmpLastWeek
Then finally I drop this temporary table so that it can be ran again
drop table #tmpLastWeek
Any advice or suggestions on getting this query to be ran thru and SQL connection in Excel would be much appreciated! Thanks!!!!

R and MSSQL - communication with temp tables (table not found on channel)

I'm trying to update global temp table using RODBC in a following way:
library(RODBC)
channel <- odbcConnect("RDataSource", uid = "user", pwd = "password")
query <- "select * from ##TempTable"
table_data <- sqlQuery(channel, query)
# data frame creation
sqlUpdate(channel, data_frame, index = "id", verbose = TRUE, tablename = "##TempTable")
Select query executes well, but sqlUpdate is failed with error message:
"Error in odbcTableExists(channel, tablename) : ‘##TempTable’: table not found on channel"
I suppose that the reason of this error may be connected with using of '#' in the name of temp tables.
UPD: I'm getting the same error with sqlSave function. This error occures only when I'm creating temp table, everything is ok with usual SQL tables.
Global temp table is creating before the calling of R code.
So, is there any way to communicate with temp tables in MSSQL database using R functions such as sqlSave() and sqlUpdate()?
I finally found that the cause of this error was in the settings of ODBC Data Source. It seems that communication with temp tables using R functions such as sqlSave or sqlUpdate requires the default database in ODBC data source to be set to 'tempdb'.
So, now I'm able to use sqlSave() function to insert values in temp table. This function in fact has much better performance than using sqlQuery function with the direct 'INSERT' query as a parameter.