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

abdelfattah khatab 20 Reputation points
2023-11-07T10:56:10.17+00:00

Hello,

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.Connection.Open();
    comm.CommandTimeout = this.sqlCommandTimeout;
    comm.ExecuteNonQuery();
}

Do you have any suggestions for resolving this issue?

Thank you in advance.

C#
C#
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.
10,851 questions
Transact-SQL
Transact-SQL
A Microsoft extension to the ANSI SQL language that includes procedural programming, local variables, and various support functions.
4,625 questions
{count} votes

Accepted answer
  1. Karen Payne MVP 35,401 Reputation points
    2023-11-07T11:36:03.37+00:00

    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 44,306 Reputation points
    2023-11-07T11:43:47.86+00:00

    "USE [INVOICES]."

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


Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.