Sql error near table syntax error

With SQL Server's quoted_identifier option set to Off, you may receive the following error:

Symptoms

With SQL Server’s quoted_identifier option set to Off, you may receive the following error:

Run-time error ‘-2147217900 (80040e14)’:
Line 1: Syntax error near ‘tablename’

This error occurs when you are using client-side cursors with the Microsoft OLE DB Provider for SQL Server (SQLOLEDB). The error occurs on an ActiveX Data Objects (ADO) recordset’s Update method and may occur on an AddNew method.

Cause

With ADO client-side cursors, when you invoke an ADO recordset’s AddNew or Update method, the OLE DB Provider prepares a SQL statement to send to SQL Server.

The Microsoft OLE DB Provider for SQL Server automatically quotes identifiers on an ADO recordset’s Update method and may quote identifiers on an AddNew method. Identifiers include table names and field names.

For example, updating the Titles table in the Pubs database with the following code:

MyADORecordet.Update

The preceding would be prepared similar to the following:

UPDATE "titles" SET "title"='Hello World' WHERE "title_id"='3'

Note that the table name is in quotes, «titles», and that each field name is in quotes, «title», «title_id», and so on.

If SQL Server’s Quoted_Identifier option is set to Off, SQL Server will not recognize table names and field names enclosed in quotes.

The error «Syntax error near ‘tablename'» occurs.

Resolution

If you do not have a reason to set quoted identifiers off, set them back on and the above error message will no longer be shown.

If it is necessary to have quoted identifiers set off, following are two workarounds that allow you to set the quoted_identifier option off and update records using ADO recordsets:

  • Use server-side cursors.

    For example, before opening an ADO Connection object named cn, use the following syntax:

    cn.CursorLocation = adUseServer

    -or-

  • Use the Microsoft OLE DB Provider for ODBC Drivers with the Microsoft SQL Server ODBC Driver.

    By default, the SQL Server ODBC driver quotes identifiers. However, you may configure the SQL Server ODBC driver to prepare SQL statements without quoted identifiers.

    NOTE: You must use the SQL Server ODBC driver 2.65.0240 that ships with the SQL Server 6.5 Service Pack 2, or a later driver. Earlier SQL Server ODBC drivers do not have this capability.

    1. Add «QuotedID=No» in the ODBC connection string.

      -or-

    2. Clear Use ANSI Quoted Identifiers in the Microsoft SQL Server Data Source Name (DSN) Configuration.

      1. Open the ODBC Administrator.

      2. Open the User DSN or System DSN that you are using to connect to your SQL Server database.

      3. Click Next until you reach the dialog box with Use ANSI Quoted Identifiers.

      4. Clear the check box next to Use ANSI Quoted Identifiers.

      5. Click Finish.

NOTE: Examples of both workarounds are shown in the «More Information» section.

Status

This behavior is by design.

More Information

ADO and the underlying OLE DB Provider are not aware of the SQL Server setting for the quoted_identifier, as set by the Transact SQL (T-SQL) statements:

  • Set quoted_identifier Off

    -or-

  • Set quoted_identifier On

ADO’s client-side quoted identifier behavior is derived from the underlying OLE DB provider. Therefore, to use client-side cursors, you must configure the Provider to quote or not to quote identifiers, depending on the SQL Server setting for quoted_identifier.

The OLE DB Provider for SQL Server automatically quotes identifiers to ensure that if the identifier contains a special character, it will be quoted, as required by SQL Server. Note that the identifier does not have to actually contain a special character. It is only the possibility that causes the OLE DB Provider to quote the identifier. The OLE DB Provider for SQL Server does not have a property to explicitly specify that identifiers should or should not be quoted.

You can configure the OLE DB provider for ODBC to prepare SQL statements with or without quotes around identifiers. It uses the ODBC driver setting for QuotedID to determine whether to quote identifiers. For this reason, you may include the «QuotedID=Yes» or «QuotedID=No» option in the ODBC connect string, or select/deselect «Use ANSI Quoted Identifiers» in a DSN setup. Note that, by default, «QuotedID=Yes», instructing the ODBC to quote identifiers.

When you use ADO server-side cursors, cursors open on the server. The OLE DB Provider prepares the T-SQL sp_cursoropen, sp_cursorfetch, and related server-side cursor statements, instead of action queries.

The ADO Connection object’s «Quoted Identifier Sensitivity» property shows the configuration a Provider uses to quote identifiers. The «Quoted Identifier Sensitivity» property is read-only, and only available at run- time after the Connection object has been opened. The «Quoted Identifier Sensitivity» property is only available for certain Providers, including the SQL Server and ODBC Providers. Since the property is read-only, you cannot use the «Quoted Identifier Sensitivity» property to configure a Provider to quote or not quote identifiers.

The ADO Connection object’s read-only «Quoted Identifier Sensitivity» property will be as follows:
8 — When the Provider is configured to quote identifiers.
0 — When the Provider is configured not to quote identifiers.

Steps to Reproduce Behavior

NOTE: In the following code examples, substitute your server’s name for servername in the connection strings.

This example uses the Pubs database that comes with SQL Server.

  1. Create the user interface:

    1. In Visual Basic, create a new Standard .exe project. Form1 is created by default.

    2. Add a Command button to Form1.

  2. Set a Reference to the Microsoft ActiveX Data Objects Library.

  3. Copy and paste the following code into the Click event of Command1.

    Note You must change User ID <username> and Password <strong password> to the correct values before you run this code. Make sure that User ID has the appropriate permissions to perform this operation on the database.

    Dim strcn As String
    Dim cn As New ADODB.Connection
    Dim rs As New ADODB.Recordset

    strcn = "Provider=SQLOLEDB;User ID=<user name>;Password=<strong password>;Initial Catalog=Pubs;"
    strcn = strcn & "Data Source=servername"

    cn.ConnectionString = strcn

    'Error occurs with Client-side cursors.
    cn.CursorLocation = adUseClient

    cn.Open

    'Instruct SQL Server to turn off Quoted_Identifier.
    cn.Execute "set quoted_identifier off"

    rs.Open "select * from titles", cn, adOpenKeyset, adLockOptimistic
    rs(1).Value = "Hello World"

    'Error occurs on this line.
    rs.Update

    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing

  4. Test the application with the following:

    1. Optionally, start the SQL Server SQLTrace program on the server. SQLTrace is a standalone program in the SQL Server 6.5 group. SQLTrace allows you to view the SQL statements that arrive at the SQL Server.

    2. In Visual Basic, clicking the Command button at run-time causes the following error:

      Run-time error '-2147217900 (80040e14)':
      Line 1: Syntax error near 'tablename'

    3. If you are using SQLTrace, you may examine the T-SQL UPDATE statement that the OLE DB Provider for SQL Server created. Note that table names and field names appear in quotes.

Examples of Workarounds

Using the OLE DB Provider for ODBC Drivers (MSDASQL)

You must use the SQL Server ODBC driver 2.65.0240 that ships with SQL Server 6.5 Service Pack 2, or a later driver.

Modify the connection string in the preceding example to the following.

Note You must change UID <username> and PWD <strong password> to the correct values before you run this code. Make sure that UID has the appropriate permissions to perform this operation on the database.
strcn = «Provider=MSDASQL;driver=SQL Server;UID=<user name>;PWD=<strong password>;»
strcn = strcn & «DATABASE=pubs;SERVER=servername;QuotedId=No»

Using Server-Side Cursors

Modify the cn.CursorLocation in the preceding example to the following:
cn.CursorLocation = adUseServer
If you are using the SQL Server SQLTrace program, you may examine the T-SQL sp_cursor statements that the OLE DB Provider creates.

References

SQL Server Books Online; search on: «quoted_identifier.»

For a discussion of configuring the SQL Server ODBC Driver with quoted_identifier on or off, please see the following article in the Microsoft Knowledge Base:

135533INF: Differences in SQL Behavior Between ODBC and ISQL

Need more help?

So, you’re creating a custom SQL query to perform a task in the database. After putting the code together and running it in PHPmyAdmin it responds with a 1064 error. It may look similar to this:

1064 error message

The 1064 error displays any time you have an issue with your SQL syntax, and is often due to using reserved words, missing data in the database, or mistyped/obsolete commands. So follow along and learn more about what the 1064 error is, some likely causes, and general troubleshooting steps.

Note: Since syntax errors can be hard to locate in long queries, the following online tools can often save time by checking your code and locating issues:

  • PiliApp MySQL Syntax Check
  • EverSQL SQL Query Syntax Check & Validator

Causes for the 1064 error

  • Reserved Words
  • Missing Data
  • Mistyped Commands
  • Obsolete Commands

This may seem cryptic since it is a general error pointing to a syntax issue in the SQL Query statement. Since the 1064 error can have multiple causes, we will go over the most common things that will result in this error and show you how to fix them. Follow along so you can get your SQL queries updated and running successfully.

Using Reserved Words

Every version of MySQL has its own list of reserved words. These are words that are used for specific purposes or to perform specific functions within the MySQL engine. If you attempt to use one of these reserved words, you will receive the 1064 error. For example, below is a short SQL query that uses a reserved word as a table name.

CREATE TABLE alter (first_day DATE, last_day DATE);

How to fix it:

Just because the word alter is reserved does not mean it cannot be used, it just has special requirements to use it as the MySQL engine is trying to call the functionality for the alter command. To fix the issue, you will want to surround the word with backticks, this is usually the button just to the left of the “1” button on the keyboard. The code block below shows how the code will need to look in order to run properly.

CREATE TABLE `alter` (first_day DATE, last_day DATE);

Missing Data

Sometimes data can be missing from the database. This causes issues when the data is required for a query to complete. For example, if a database is built requiring an ID number for every student, it is reasonable to assume a query will be built to pull a student record by that ID number. Such a query would look like this:

SELECT * from students WHERE studentID = $id

If the $id is never properly filled in the code, the query would look like this to the server:

SELECT * from students WHERE studentID =

Since there is nothing there, the MySQL engine gets confused and complains via a 1064 error.

How to fix it:

Hopefully, your application will have some sort of interface that will allow you to bring up the particular record and add the missing data. This is tricky because if the missing data is the unique identifier, it will likely need that information to bring it up, thus resulting in the same error. You can also go into the database (typically within phpMyAdmin) where you can select the particular row from the appropriate table and manually add the data.

Mistyping of Commands

One of the most common causes for the 1064 error is when a SQL statement uses a mistyped command. This is very easy to do and is easily missed when troubleshooting at first. Our example shows an UPDATE command that is accidentally misspelled.

UDPATE table1 SET id = 0;

How to fix it:

Be sure to check your commands prior to running them and ensure they are all spelled correctly.

Below is the syntax for the correct query statement.

UPDATE table1 SET id = 0;

Obsolete Commands

Some commands that were deprecated (slated for removal but still allowed for a period of time) eventually go obsolete. This means that the command is no longer valid in the SQL statement. One of the more common commands is the ‘TYPE‘ command. This has been deprecated since MySQL 4.1 but was finally removed as of version 5.1, where it now gives a syntax error. The ‘TYPE‘ command has been replaced with the ‘ENGINE‘ command. Below is an example of the old version:

CREATE TABLE t (i INT) TYPE = INNODB;

This should be replaced with the new command as below:

CREATE TABLE t (i INT) ENGINE = INNODB;

For developers or sysadmins experienced with the command line, get High-Availability and Root Access for your application, service, and websites with Cloud VPS Hosting.

Error 1064 Summary

As you can see there is more than one cause for the 1064 error within MySQL code. Now, you know how to correct the issues with your SQL Syntax, so your query can run successfully. This list will be updated as more specific instances are reported.

It is SQL 2000 with SP4.

I think error is there in Stored procedure. My snapshot gives an error after table named Date Compr_ Register.

 Error is like following:

Line 38: Incorrect syntax near ‘tabl’
Preparing table Date Compr_ Register
Preparing table ——
.
.
.
.

stored procedure for this table is as follow:

create procedure dbo.[sel_C2110BDD1BF142C8ACF92DCEAE1D4175] (@tablenick int, @max_rows int = NULL,
 @guidlast uniqueidentifier = NULL)
 AS

 set nocount on
 set rowcount 0
 if  @max_rows is not null
 begin
  — used to select data for initial pop. of subscriber for dynamic filtered publication
  set rowcount @max_rows
  declare @lin varbinary (255)
  declare @cv varbinary (2048)
  declare @replnick int
  declare @objid int
  declare @ccols int

  select @objid = objid from sysmergearticles where nickname = @tablenick
  select @ccols = max(colid) from syscolumns where id = @objid

    exec dbo.sp_MSgetreplnick @nickname = @replnick out
  if (@@error <> 0) or @replnick IS NULL
  begin
   RAISERROR (14055, 11, -1)
   RETURN(1)
  end     
  set @lin = { fn UPDATELINEAGE(0x0, @replnick) }
  set @cv = { fn INITCOLVS(@ccols, @replnick) }

  select @tablenick, v.[rowguid], coalesce (c.generation,1),
   coalesce (c.lineage, @lin), coalesce (c.colv1, @cv), v.[Journal Template Name], v.[Journal Batch Name], v.[Journal Line No_], v.[Line No_], v.[Account No_], v.[Shortcut Dimension 1 Code], v.[Shortcut Dimension 2 Code], v.[Allocation Quantity], v.[Allocation %], v.[Amount], v.[Gen_ Posting Type], v.[Gen_ Bus_ Posting Group], v.[Gen_ Prod_ Posting Group], v.[VAT Calculation Type], v.[VAT Amount], v.[VAT %], v.[Tax Area Code], v.[Tax Liable], v.[Tax Group Code], v.[Use Tax], v.[VAT Bus_ Posting Group], v.[VAT Prod_ Posting Group], v.[Additional-Currency Amount], v.[rowguid] from [dbo].[Windowmaker Software Limited$Gen_ Jnl_ Allocation] v left outer join  dbo.MSmerge_contents c on
       v.[rowguid] = c.rowguid  and c.tablenick = @tablenick where v.[rowguid] > @guidlast
      order by v.[rowguid]
  return (1)  
 end

 insert into #belong (tablenick, rowguid, flag, skipexpand, partchangegen, joinchangegen)
  select ct.tablenick, ct.rowguid, 0, 0, ct.partchangegen, ct.joinchangegen
     from  #contents_subset ct, [dbo].[Windowmaker Software Limited$Gen_ Jnl_ Allocation] v where ct.tablenick = @tablenick- Line 38.
     and ct.rowguid = v.[rowguid] 
 if @@ERROR <> 0
  begin
  RAISERROR(‘Error selecting from view’ , 16, -1)
  return (1) 
  end
GO

I am not getting what is the meaning of the code.
Please help.

  Last tested: Feb 2021

Overview

This SQL error generally means that somewhere in the query, there is invalid syntax.
Some common examples:

  • Using a database-specific SQL for the wrong database (eg BigQuery supports DATE_ADD, but Redshift supports DATEADD)
  • Typo in the SQL (missing comma, misspelled word, etc)
  • Missing a sql clause (missed from, join, select, etc)
  • An object does not exist in the database or is not accessible from the current query (eg referencing orders.id when there is no orders table joined in the current query, etc)

In some circumstances, the database error message may display extra detail about where the error was raised, which can be helpful in narrowing down where to look.

Error Message

SQL ERROR: syntax error at or near

Troubleshooting

This should generally be the first step to troubleshoot any SQL syntax error in a large query: iteratively comment out blocks of SQL to narrow down where the problem is.

TIP: To make this process easier, change the group by clause to use position references
eg: group by 1,2,3,4,5 instead of group by orders.status, orders.date, to_char(...)...
as well as separate the where and having clauses onto multiple lines.

So for example, say we have the following query:

play_arrow

WITH cte AS (
select id, status, sales_amountfrom orders
)
select status, foo.date, sum(cte.sales_amount), count(*) from cte
join foo on cte.date = foo.date
group by status, foo.date
order by 3 desc

We could start by running just the portion in the CTE:

play_arrow

-- WITH cte AS (
select id, status, sales_amountfrom orders
-- )
-- select status, foo.date, sum(cte.sales_amount), count(*)
-- from cte
-- join foo on cte.date = foo.date
-- group by 1, 2
-- order by 3 desc

Then strip out the aggregates and portions related to them

play_arrow

WITH cte AS (
select id, status, sales_amountfrom orders
)
select status, foo.date, -- sum(cte.sales_amount), count(*)
from cte
join foo on cte.date = foo.date
-- group by 1, 2
-- order by 3 desc

Iteratively stripping out / adding back in portions of the query until you find the minimum query to trigger the error.

  • Lookup functions and syntax If the query is small enough, or if we’ve narrowed the scope enough with 1, google all the functions used in the query and verify that they exist and are being used correctly.

  • Verify all objects exist Verify that you’ve joined all tables used in the select, where, and having clause, and that those tables exist in the db. Once we’ve narrowed things down from 1, also check that each column exists in the table specified.

Понравилась статья? Поделить с друзьями:
  • Sql error library routine called out of sequence
  • Sql error invalid cursor
  • Sql error invalid column name
  • Sqlite error or missing database
  • Sqlite error no such column