How do I fix incorrect syntax near SQL Server?

4.2K    Asked by CamelliaKleiber in SQL Server , Asked on Apr 24, 2021

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.

Answered by bhushan bhad

To fix incorrect syntax near SQL Server, you may need to set the compatibility level of the current database to a higher value to enable this feature. While it's certainly possible that someone changed your stored procedure and broke it in the process, the simplest explanation for something like this breaking is a change in the input data that causes it to break. In the comments, a number of people tried your stored procedure in various versions of SQL Server, and it ran successfully. This makes it even more likely that the problem is a change in the data being provided to the stored procedure. If you can think of a table that's using a data type that none of your tables has used before, that could cause your procedure to start running a branch that it had never needed to run before, causing an error. You can troubleshoot this using the following steps: You've already got a statement that prints out the dynamic SQL you execute to your "Messages" window in SSMS before it executes it. Look at the output in that window carefully. Are any tables processed, or are you failing on the very first table? If you are failing on the very first table, before @script_sql is even printed once, then try running the stored procedure manually. Using SSMS, in the Object Explorer window: open a Database Engine connection to your server; expand your server; then Databases; then your database; then Programmability; then Stored Procedures. Right-click on your stored procedure, and select "Script Stored Procedure As", "CREATE To", "New Query Editor Window". In the query editor window, modify the code that creates your stored procedure so you can run the code directly. remove or comment out the CREATE PROCEDURE line; change the parameter list to DECLARE statements; and comment out or remove the AS. Figure out the first table name your script is trying to process. Manually set @nom_table to this table name in your DECLARE statement (or in a SET statement right afterward). Now, run the modified code from your stored procedure. See exactly where it stops (add additional PRINT statements if necessary to determine exactly where it stops). If you get to the point where @script_sql is printed out, try copying the statement and running that manually, in a new query window. If that fails, look at the SQL statement carefully. Get the length of @script_sql, and compare that with what was output; beyond a certain length, PRINT will truncate your value (so you wouldn't be getting all of @script_sql in the "Messages" window). You can overcome this by printing substrings of @script_sql If you don't see any obvious errors in the statement, try running parts of it only. Can you create the table with just the first column? just the first two? etc. As you include additional columns, you will eventually find one or more that are causing issues. For each test, start from the full code in @script_sql, to minimize the likelihood of introducing errors by repeated cutting and pasting. One of the current answers points out a couple of potential issues in your code; I'll point out one more. I don't think the line:

set  @script_sql= case
                    when left(@script_sql,1)=','
                      then left(@script_sql, LEN(@script_sql) -1)
                    else @script_sql
                  end + ') '

is working as you'd expect it to. I believe it's intended to strip a trailing comma from the SQL statement before adding the closing parenthesis. However, it's actually checking if the first character in @script_sql is a comma, not the last. Try this instead:

set  @script_sql= case
                    when right(@script_sql,1)=','
                      then left(@script_sql, LEN(@script_sql) -1)
                    else @script_sql
                  end + ') '

Finally - you can get an idea of whether anyone has changed your procedure from SSMS. If you don't still have everything expanded, follow the directions from step 2 above to expand your server and database to the point where you see the "Stored Procedures" folder. Left-click on the folder, then go to the "Windows" menu and choose "Object Explorer Details". You'll get a view of your stored procedure that includes "Create Date" and "Date Last Modified" (if you don't see those, right-click on the headers for the columns you do see, and select those columns so you can see them.) Check the create date and last modified date for the procedure; has it been changed recently? If so, then hopefully you have an old version of the stored procedure in a text or .sql file somewhere; or, you have an old backup of your database (you can restore this under a different name, and script out the stored procedure from the backup. You can then remove the old restored DB, and try the older version of the stored procedure, to see if it works). You should also be using NVARCHAR for all of this instead of VARCHAR. And change the declaration of @code_colonne VARCHAR(1000) to be NVARCHAR(MAX). Something might be being silently truncated, or how code_colonne is being built, such as a blank or still NA (instead of a NULL) for Longest causing the resulting type to be either CHAR() or CHAR(NA). You could also run a Profiler trace, to see what's going on during the procedure execution.



Your Answer

Answer (1)

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.








3 Months

Interviews

Parent Categories