Incorrect syntax while accessing SQL table using Python - sql

I'm trying to access a SQL Express database using Python, but I keep getting an incorrect syntax error. I've tried a few variations based of other examples I've seen, but nothing's working.
import pyodbc
conn = pyodbc.connect(Trusted_connection='yes',
driver='{SQL Server}',
server='VACE1\RCARCHIVE',
database='TestDB')
cursor = conn.cursor()
cursor.execute("select * from 100000MTL1")
for row in cursor:
print(row)
The error is
pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC SQL Server Driver][SQL Server]Incorrect syntax near '100000'. (102) (SQLExecDirectW)")
I've tried changing the database and the name of the database, but I'm not sure if that is where the error is exactly, so I'm totally stuck now.

Escape your table name like this
select * from [100000MTL1]
since table names usually don't start with numbers.

Related

Failed to run inner join to fetch data (from a Microsoft Server) using RStudio SQL tool (w/ good db connection)

Here is my problem: I'm using R-SQL tool to fecth data from a server. Although my db connection is good, and I can run query against each individual table, I couldn't run inner join of two tables using the same R-SQL tool, ie., dbconnent (from DBI) and sqlQuery(from RODCB)
Here is the error message when running dbconnent(): "Error: nanodbc/nanodbc.cpp:1655: 42000: [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Incorrect syntax near the keyword 'Key'. [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared. "
Here are abbreviated codes
----
sql1 <- "
SELECT
e.RID, e.Form,
i.ItemName, i.Response
FROM ExamResult AS e
INNER JOIN ItemResult AS i
ON e.RID=i.RID
WHERE e.ExamSeriesCode= 'Exam1'
"
result <- dbGetQuery(conn, sql1)
Thank you!
To debug, I ran query against each individual table, it went fine.
I checked the linking var (RID" in each table, they have identical name and property.
I tried both dbconnent (from DBI) and sqlQuery(from RODCB). the same problem ( not running inner join) persists.
Your error message includes a reference to Key,
Error: nanodbc/nanodbc.cpp:1655: 42000: [Microsoft][ODBC Driver 17 for SQL
Server][SQL Server]Incorrect syntax near the keyword 'Key'. [Microsoft][ODBC
Driver 17 for SQL Server][SQL Server]Statement(s) could not be prepared.
This suggests your real query has Key in it. This is a reserved word in SQL, requiring that it be escaped. Most DBMSes do this by using brackets around the reserved word to clearly identify it as a SQL Identifier (as opposed to a Literal, such as the string value 'hello').
Bottom line, in your real query, replace Key with [Key] (or "Key").
To do this programmatically (and confirm that in fact brackets work with your specific DBMS), you can use:
DBI::dbQuoteIdentifier(con, "Key")
# <SQL> "Key"
which doesn't seem to tell you much, but the double quotes are real.
as.character(DBI::dbQuoteIdentifier(con, "Key"))
# [1] "\"Key\""
Many (including SQL Server) will accept both [Key] and "Key" without ambiguity.

PostgreSQL - Failed to prepare query: ERROR: column "referenceno" does not exist

This is probably a really obvious mistake, but I have been trying a number of things and I do not seem to be able to get the right answer.
From R, I try to execute the following DELETE SQL statement on a PostgreSQL database hosted by Digital Ocean.
sql <- "DELETE FROM tablename WHERE referenceNo IN (380,376,344,345)"
conn %>% dbExecute(sql)
I get the following error and I am unable to find the correct syntax.
Error: Failed to prepare query: ERROR: column "referenceno" does not exist
LINE 1: DELETE FROM tablename WHERE referenceNo IN (380,37...
^
HINT: Perhaps you meant to reference the column "tablename.referenceNo".
I have tried to follow the hint and tried SQL syntax like:
sql <- "DELETE FROM tablename WHERE tablename.referenceNo IN (380,376,344,345)"
Unfortunately, I get the same error message.
i already slove a problem like your's by using : "columns" and not columns,
DELETE FROM tablename WHERE "referenceNo" IN (380,376,344,345)

"Incorrect syntax near the keyword 'User'." error on SQL Server

I'm getting an error at this statement:
cursor.execute("SELECT * FROM dbo.User")
Error:
pyodbc.ProgrammingError: ('42000', "[42000] [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Incorrect syntax near the keyword 'User'. (156) (SQLExecDirectW)")
The code is below. I'm assuming the connection is fine because nothing happens unless I execute the query? Am I doing something wrong?
SERVER = 'LAPTOP-1E7UL24T\SQLEXPRESS02'
DATABASE = 'PT'
DRIVER='{ODBC Driver 17 for SQL Server}'
DATABASE_CONNECTION=f'Driver={DRIVER};SERVER={SERVER};Database={DATABASE};Trusted_Connection=yes;'
print(DATABASE_CONNECTION)
cnxn=pyodbc.connect(DATABASE_CONNECTION)
cursor=cnxn.cursor()
cursor.execute("SELECT * FROM dbo.User")
User is a reserved word and needs to be escaped, commonly by using square brackets e.g.
SELECT * FROM dbo.[User]
But double quotes also work:
SELECT * FROM dbo."User"
Although it will make your life (and any developers who follow) a lot easier if you just avoid using reserved words.
Most likely you are running into the deprecated data types: IMAGE, TEXT and NVARCHAR. They need to be handled differently.
See their github issue, and this SO answer.

Incorrect syntax near ')' in SQL Server

I am getting an error:
Incorrect syntax near ')'
while trying to run the SQL query shown below on SAP Business Objects Information design tool. The query executes just fine from SQL Server, but from SAP Information design tool, I get this incorrect syntax error while trying to see the table values.
SQL Error:
Valid SQL
;WITH XMLNAMESPACES('Callaway.CRM.DAL.Objects.VisitActivityDetail' as ns)
SELECT
r.value('(ns:*)[3]','nvarchar(1000)') AS VisitType
FROM
Activity
OUTER APPLY
XML.nodes('/ns:VisitActivityDetail/ns:VisitType') AS x(r)
WHERE
ActivityTypeID = 2
Can you please help me understand what is wrong here?

DB2 SQL Error: SQLCODE=-901, SQLSTATE=58004, SQLERRMC=Invalid collation ID, DRIVER=4.21.29

Trying to execute the statement
select *
from RU_VARIANCE_HISTORY
but I'm getting the error
DB2 SQL Error: SQLCODE=-901, SQLSTATE=58004,
SQLERRMC=Invalid collation ID, DRIVER=4.21.29
Tried searching but unable to find the solution.
This can happen if DB2 thinks the statement is really too long or too short. Try adding a semicolon to the end of your statement - this worked for me with the same error.