Ask a Question
Ask Question Login
Corporate Training
  1. Community
  2. SQL Server
  3. Question
SQL Server

How do I fix incorrect syntax near SQL Server?

Asked by Camellia Kleiber Apr 24, 2021 8.6K views 2 answers
Share

About this question

I'm trying to execute the following stored procedure:

CREATE PROCEDURE dbo.Compress_taille(@nom_table VARCHAR(64)) AS PRINT @nom_table declare @results table ( TableName varchar(250), ColumnName varchar(250), DataType varchar(250), MaxLength varchar(250), Longest varchar(250), SQLText varchar(250), position float ) INSERT INTO @results(TableName,ColumnName,DataType,MaxLength,Longest,SQLText,position) SELECT Object_Name(c.object_id) as TableName, c.name as ColumnName, t.Name as DataType, case when t.Name not like '%char%' Then 'NA' when c.max_length = -1 then 'Max' else CAST(c.max_length as varchar) end as MaxLength, 'NA' as Longest, 'SELECT Max(Len([' + c.name + '])) FROM ' + OBJECT_SCHEMA_NAME(c.object_id) + '.' + Object_Name(c.object_id) as SQLText, column_id as position FROM sys.columns c INNER JOIN sys.types t ON c.system_type_id = t.system_type_id WHERE c.object_id = OBJECT_ID(@nom_table) and t.Name <> 'sysname' order by column_id DECLARE @position varchar(36) DECLARE @sql varchar(200) declare @receiver table(theCount int) DECLARE cursor_script CURSOR FOR SELECT position, SQLText FROM @results WHERE MaxLength != 'NA' OPEN cursor_script FETCH NEXT FROM cursor_script INTO @position, @sql WHILE @@FETCH_STATUS = 0 BEGIN INSERT INTO @receiver (theCount) exec(@sql) UPDATE @results SET Longest = (SELECT theCount FROM @receiver) WHERE position = @position DELETE FROM @receiver FETCH NEXT FROM cursor_script INTO @position, @sql END CLOSE cursor_script DEALLOCATE cursor_script DECLARE @script_sql varchar(max) set @script_sql=' create table [AQR_INF_2017T2].[dbo].'+ left(@nom_table, LEN(@nom_table)-LEN('39CR_201703')) +'39CR_201706(' DECLARE @TableName VARCHAR(80), @ColumnName VARCHAR(80), @DataType VARCHAR(80), @MaxLength VARCHAR(80), @Longest VARCHAR(80), @code_colonne VARCHAR(1000) DECLARE getemp_curs CURSOR FOR SELECT TableName, ColumnName, DataType,MaxLength, coalesce(case when Longest='0' then '10' else Longest end ,'1') as Longest, position, coalesce( case when DataType like '%numer%' then '[' + ColumnName + '] float,' when DataType like '%char%' then '[' + ColumnName + '] char(' + coalesce(case when Longest='0' then '10' else Longest end ,'1') + '), ' else '[' +ColumnName + '] ' + DataType+ ',' end,'[' +ColumnName + '] nvarchar(1),') AS code_colonne FROM @results order by position OPEN getemp_curs FETCH NEXT FROM getemp_curs into @TableName, @ColumnName, @DataType,@MaxLength,@Longest,@position,@code_colonne WHILE @@FETCH_STATUS = 0 BEGIN set @script_sql=@script_sql + @code_colonne FETCH NEXT FROM getemp_curs into @TableName, @ColumnName, @DataType,@MaxLength,@Longest,@position,@code_colonne END CLOSE getemp_curs DEALLOCATE getemp_curs set @script_sql= case when left(@script_sql,1)=',' then left(@script_sql, LEN(@script_sql) -1) else @script_sql end + ') ' PRINT '@script_sql: ' + @script_sql exec @script_sql GO

But I when I execute this code:

DECLARE @table varchar(255) DECLARE cursor_test CURSOR FOR SELECT name FROM sysobjects WHERE type='U' and substring(name,1,3) not in ('T_P','T_Z','T_R','TEST_AQR') order by name -- SUPPRIME LES TABLES NON UTILES POUR L'INFOCENTRE AQR OPEN cursor_test FETCH NEXT FROM cursor_test INTO @table WHILE @@FETCH_STATUS = 0 BEGIN EXEC AQR_INF_2017T2.dbo.Compress_taille @table FETCH NEXT FROM cursor_test INTO @table END CLOSE cursor_test DEALLOCATE cursor_test I get this error message: Msg 102, Level 15, State 1, Line 1 Incorrect syntax near ')'. This code was working for one year and now it doesn't. Our version control does not seem to help either, and, unfortunately, the logic does not seem straightforward to me. One thought was about the version of SQL Server causing breaking changes, but I am not convinced. How would I go about troubleshooting this issue? Are there any good industry practices for tracking down script issues when dynamic sql is involved? I need to verify where the breaking code starts, not necessarily where the syntax error occurs.

Your answer

2 Answers

Ranjana Admin JanBask Expert Latest answer

Answered on Jul 3, 2024

Fixing the "Incorrect syntax near" error in SQL Server involves identifying and correcting the syntax error in your SQL query. Here are some steps to help you troubleshoot and resolve this issue:

1. Review the Error Message

First, carefully review the error message returned by SQL Server. It typically includes a description of where the syntax error occurs in your query, such as a specific line or near a particular keyword.

2. Check for Typos and Misspellings

Ensure that there are no typos or misspellings in your SQL query, especially around keywords like SELECT, FROM, WHERE, JOIN, INSERT INTO, UPDATE, DELETE, etc. Even minor mistakes can cause syntax errors.

3. Verify SQL Server Compatibility

If you are using advanced features or functions, ensure that your SQL Server version supports them. Some features may not be available in older versions of SQL Server.

4. Use SQL Server Management Studio (SSMS) for Syntax Highlighting

If possible, write and test your SQL queries in SQL Server Management Studio (SSMS) or another SQL editor that provides syntax highlighting and error checking. This can help you spot syntax errors before executing the query.

5. Check Reserved Keywords

Ensure that you are not using SQL Server reserved keywords as identifiers (e.g., table names, column names) without enclosing them in square brackets ([]). Reserved keywords should be used with caution to avoid syntax errors.

6. Verify Quotes and String Formatting

If your SQL query includes string literals or identifiers that require quotes (e.g., 'string', "column"), ensure that they are properly formatted and closed. Mismatched quotes can lead to syntax errors.

7. Check Semi-Colon Placement

In some cases, SQL Server requires semi-colons (;) to separate SQL statements, especially when multiple statements are executed together (e.g., in a batch or stored procedure). Ensure correct semi-colon placement where necessary.

8. Test the Query in Parts

If your query is complex, try breaking it down into smaller parts and testing each part separately. This can help isolate and identify the specific part of the query causing the syntax error.

9. Use SQL Server Profiler for Tracing Errors

SQL Server Profiler can be used to trace and identify syntax errors in your queries by capturing SQL Server events and error messages in real-time.

Example Scenario:

Suppose you have a query that generates the error "Incorrect syntax near 'WHERE'":

  SELECT FirstName, LastNameFROM EmployeesWHERE Department = 'IT'AND Salary > 50000;In this example, ensure that:Employees is a valid table.

Department and Salary are valid column names in the Employees table.

The semicolon (;) is correctly placed if this query is part of a batch.

Conclusion:

By following these steps and carefully reviewing your SQL query, you should be able to identify and fix the "Incorrect syntax near" error in SQL Server. Pay attention to details such as correct syntax, proper use of keywords, and consistent quoting to ensure your queries execute successfully. If you encounter persistent issues, reviewing the SQL Server documentation or seeking assistance from a database administrator (DBA) can also be beneficial.








Was this helpful?

More SQL Server discussions

Learn & Explore

Free tutorials and interview questions from industry experts — learn the skill, then get ready to prove it.

Latest SQL Server Blogs

Guides, tips and career advice on SQL Server from JanBask experts.