Error: "System.Data.SqlClient.SqlException: 'Incorrect syntax near ''.' "

abdelfattah khatab 20 Reputation points


I have an SQL script in a file that I want to execute through a .NET 6 application, processing it line by line. The script begins with the command "USE [INVOICES]." However, when I launch the application, I get the following error message:

"System.Data.SqlClient.SqlException: 'Incorrect syntax near ''.' "

The line causing the error is the first line "USE [INVOICES]"

Here is the C# code I am using:

the value of sql variable is "USE [INVOICES]"

using (SqlCommand comm = new SqlCommand(sql, cn))
    if (comm.Connection.State != ConnectionState.Open)
    comm.CommandTimeout = this.sqlCommandTimeout;

Do you have any suggestions for resolving this issue?

Thank you in advance.

An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
9,469 questions
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,459 questions
{count} votes

Accepted answer
  1. Karen Payne MVP 34,591 Reputation points

    Without seeing the entire script, there is no reason to have USE [INVOICES] in the script as this is the responsibility of the connection to set the Initial Catalog as part of the connection string.

    1 person found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. Olaf Helper 36,091 Reputation points


    Is there really a dot at the end / after [INVOICES]? That's not valid, remove it.