Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

R ODBC - Querying Column name with spaces

Tags:

sql

r

rodbc

I am trying to query through R OBDC. But one Column name has space on it. For example, [Account No].

I am using this code to query:

esiid_ac <- sqlQuery(myconn, paste("
 SELECT * FROM CustomerUsage WHERE ((CustomerUsage.Account No ='", 12345, "')) ", sep=""),as.is=TRUE)

I am getting the following error:

[1] "42000 102 [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Incorrect syntax near 'No'." [2] "[RODBC] ERROR: Could not SQLExecDirect '\n SELECT * FROM CustomerUsage WHERE ((CustomerUsage.Account No ='678987')) '

How to solve this?

Can I read this table with column index instead of column names?

Thank you.

like image 338
Sripati Avatar asked Jun 21 '17 17:06

Sripati


3 Answers

After tinkering around with quotes a little bit, this worked for me:

df <- sqlQuery(myconn, 'SELECT * FROM mytable WHERE "column name" =123', as.is=TRUE)
like image 129
Thorsten Avatar answered Oct 17 '22 10:10

Thorsten


Have you tried square brackets (They work for me when there are special characters in column names)?

esiid_ac <- sqlQuery(myconn, paste(" SELECT * FROM CustomerUsage WHERE ((CustomerUsage.[Account No] ='", 12345, "')) ", sep=""),as.is=TRUE)
like image 2
Golden Ratio Avatar answered Oct 17 '22 11:10

Golden Ratio


You can use \"COL_NAME\" instead of COL_NAME and use that as you would always use it. For example:

esiid_ac <- sqlQuery(myconn, "SELECT * FROM CustomerUsage WHERE \"Account No\" = 12345")
like image 2
Dick van Huizen Avatar answered Oct 17 '22 12:10

Dick van Huizen