I have a parameterized query that looks like this:
SELECT title, html, shortname FROM dbo.Videos
WHERE Topic_ID = ? AND dbo.gradeLevelCheck(?, Grade_Lower, Grade_Upper) = 1
ORDER BY shortname ASC
When I run it from ASP, I get an error that reads:
Incorrect syntax near the keyword 'from'
The parameters are 56
and 1
(so no nulls). The stored function dbo.gradeLevelCheck
looks like this:
ALTER FUNCTION [dbo].[gradeLevelCheck]
(
@value int,
@lower int,
@upper int
)
RETURNS int
AS
BEGIN
DECLARE @result int;
IF (@lower IS NULL OR @lower <= @value) AND (@upper IS NULL OR @upper >= @value)
SET @result = 1;
ELSE
SET @result = 0;
RETURN @result;
END
It works fine if I submit it with the parameters hardcoded into the query. It also works fine if I remove the ORDER BY clause. But I can’t get it to work in this form. Can anyone help me figure out why?
EDIT: Here are some additional details. The application is written in Classic ASP with JScript. The connection is established thus:
var conn = Server.CreateObject('ADODB.Connection');
var connectionString =
'Provider=SQLOLEDB;' +
'Data Source=' + Settings.dbServer + ';' +
'Initial Catalog=' + Settings.dbCatalog + ';' +
'User Id=' + Settings.dbUser + ';' +
'Password=' + Settings.dbPass + ';' +
'Connect Timeout=15;';
conn.Open(connectionString, conn);
The code used to submit the query looks like this:
DB.query = function(query) {
...
var cmd = Server.CreateObject("ADODB.Command");
cmd.activeConnection = conn;
cmd.commandText = query;
for (var i = 1; i < arguments.length; i++) {
cmd.Parameters(i-1).value = arguments[i];
}
return cmd.Execute();
...
}
(Here, the parameters 1
and 56
are passed as additional arguments to DB.query
.)
При выполнении запроса
select
AllYears.Year,
count(FirstVisitYears.Patient) as Count
from
(select
min(extract(YEAR from ReceptionDate)) as Year,
Patient
from Receptions
where
ReceptionType like 'Первич%'
group by
Patient
) as FirstVisitYears right join
(
select distinct
extract(YEAR from ReceptionDate) as Year
from Receptions
) as AllYears on
FirstVisitYears.Year = AllYears.Year
group by
AllYears.Year
Возвращается ошибка
Помогите разобраться:)
Incorrect syntax near the keyword 'from'.
Пример работы SQLFiddle
- sql
- sql-server
- запрос
задан 22 мая 2016 в 20:31
ka6an4egka6an4eg
671 серебряный знак7 бронзовых знаков
1 ответ
Он ругается на конструкцию extract(YEAR from ReceptionDate)
.
Замените ее на YEAR(ReceptionDate) в обеих местах и все будет нормально.
Пример SqlFiddle
ответ дан 22 мая 2016 в 20:42
ApInventApInvent
3,7971 золотой знак18 серебряных знаков27 бронзовых знаков
10
-
Тогда не правильно работает запрос уже. в MySQL все верно он выдавал. Вывод должен быть 1 2 0 (по столбцам)
22 мая 2016 в 20:52
-
@ka6an4eg Поменял в примере фамилии написанные русским на транслит и все стало правильно. Я думаю, что sql fiddle просто схлопнул фамилии с одинаковым количеством символов т.к. он их не различил.
22 мая 2016 в 20:59
-
@Aplnvent да, уже разобрался) При создании таблицы указал имена в Юникоде (N’Иванова’)
22 мая 2016 в 21:04
-
@Aplnvent а скажи пожалуйста, если в создании таблицы указать «declare Orders table» , то из-за чего ошибка при выполнении запроса ?
22 мая 2016 в 21:24
-
@ka6an4eg не совсем понял вопрос… При создании таблицы вообще нет ключевого слова
declare
. Что ты хотел получить этой конструкцией?22 мая 2016 в 21:34
Incorrect syntax near is an error message in SQL Server because you’re using the wrong syntax for a SQL query or the query contains unprintable characters that are invincible to the naked eye.
This article will show you SQL statements that will lead to the “incorrect syntax near” error, and we’ll show you solutions that you can use to solve similar errors in your environment.
Before you proceed, know that we’re aware of how frustrating this error can get, and that’s why this article will analyze the “incorrect syntax near ‘ ‘ meaning” as a way to make it easy for you.
With that out of the way, launch your SQL Server, and let’s teach you “how to fix incorrect syntax near ‘ ‘ in SQL Server.
Contents
- Why Do Your SQL Statements Have an Incorrect Syntax?
- – Typographical Error in Your SQL Statement
- – Misusing a Keyword or Reserved Words
- – SQL Statements Have Misplaced Punctuation Marks
- – An Unprintable Characters in Your SQL Statement
- How To Fix the Syntax Errors in Your SQL Statements?
- – Check for Typographical Error in Your SQL Statement
- – Avoid Using Reserved Words as Your Column Names
- – Use Punctuation Marks the Right Way
- – Use a Text Editor To Show the Unprintable Characters
- Conclusion
Why Do Your SQL Statements Have an Incorrect Syntax?
Your SQL statements have an incorrect syntax because of the following:
- You have a typographical error in your SQL statement
- You’re misusing a keyword or reserved words
- Your SQL statements have misplaced punctuation marks
- You have unprintable characters in your SQL statement
– Typographical Error in Your SQL Statement
Typographical errors are a common cause of the “incorrect syntax near ‘-‘. SQL date” error in SQL Server. These errors occur when there is a mistake in the way that the SQL statement is written, such as a misspelled keyword or a missing punctuation mark.
For example, given the following SQL code that will create a “Customers” table:
CREATE TABLE Customers (
CustomerID INT PRIMARY KEY,
FirstName VARCHAR(50),
LastName VARCHAR(50),
Email VARCHAR(100),
Phone VARCHAR(20),
Address VARCHAR(200),
City VARCHAR(50),
State VARCHAR(50),
ZipCode VARCHAR(10)
);
INSERT INTO Customers (CustomerID, FirstName, LastName, Email, Phone, Address, City, State, ZipCode)
VALUES
(1, ‘John’, ‘Doe’, ‘johndoe@site.com’, ‘123-456-7890’, ‘123 Main St’, ‘New York’, ‘NY’, ‘10001’),
(2, ‘Jane’, ‘Doe’, ‘janedoe@site.com’, ‘123-456-7890’, ‘456 Elm St’, ‘Los Angeles’, ‘CA’, ‘90001’),
(3, ‘Bob’, ‘Smith’, ‘bobsmith@site.com’, ‘123-456-7890’, ‘789 Oak St’, ‘Chicago’, ‘IL’, ‘60601’),
(4, ‘Alice’, ‘Johnson’, ‘alicejohnson@site.com’, ‘123-456-7890’, ‘321 Pine St’, ‘Houston’, ‘TX’, ‘77001’);
The following SQL will result in a syntax error because there is a typographical error in the keyword “FORM” which should be “FROM”:
– Misusing a Keyword or Reserved Words
SQL Server has a list of reserved words that you cannot use as identifiers for tables, columns, or other objects. So, any attempt to use a reserved word as an identifier, can lead to the “incorrect syntax near ‘ ‘ in visual studio“.
For example, the following SQL statement will result in an error because “SELECT” and “TABLE” are reserved words that you cannot use as column names.
CREATE TABLE BIKE_TWO (
SELECT VARCHAR(15),
TABLE INT);
The following is another example, but this time, we typed the “FROM” keyword twice, and this will also cause an error.
SELECT FROM FROM Customers;
– SQL Statements Have Misplaced Punctuation Marks
A misplaced punctuation mark can cause the “incorrect syntax near ‘;’.” error in SQL Server, and this can happen when you’re trying to retrieve a record from a table.
For example, the following will result in a syntax error because the name that we’re retrieving contains quotes that cause the error. That’s because SQL will not understand how to parse the “SELECT” statement.
SELECT * FROM Customers WHERE Customers.FirstName = ‘O’Brien’
The same error will also occur in the following code and that’s because there we used a quote in the wrong way.
UPDATE Customers SET Lastname = ‘Doe’, ‘FirstName’ = ‘Jane’ WHERE CustomerID = 2;
– An Unprintable Characters in Your SQL Statement
In SQL Server, unprintable characters can cause the “incorrect syntax near ‘ ‘. in SQL Server 2019” error because they are mostly hidden, and they can alter the structure of an SQL statement. As a result, SQL Server cannot read and parse the statement correctly, so it returns a syntax error.
For example, in the following SQL, there is a Unicode character after the “e” in “Doe”, and it will cause the “incorrect syntax near” error. To confirm, copy the code, and run it against the “Customers” table that you created earlier.
SELECT * FROM Customers
WHERE LastName = ‘Doe’•
How To Fix the Syntax Errors in Your SQL Statements?
To fix the syntax errors in your SQL statements, you can:
- Check for a typographical error in your SQL statement
- Avoid using reserved words as your column names
- Use punctuation marks the right way
- Use a text editor to show the unprintable characters
– Check for Typographical Error in Your SQL Statement
Your first routine when you see the “incorrect syntax near” error is to check your SQL statements for typographical errors.
For example, the following code is a previous example that resulted in the error:
The next SQL is the correct version of the statement, and the fix is to change “FORM” to “FROM”. This will make it a valid SQL that the SQL server will parse without throwing a syntax error.
– Avoid Using Reserved Words as Your Column Names
Another way to prevent the incorrect syntax error in SQL Server is to avoid using reserved words as your column names. It’s recommended to use descriptive names that will make maintenance easy for you and other developers in the future.
However, if you need a reserved word as a column name, there is a way to do that.
For reference, the following is a previous example that’s trying to create the BIKE_TWO table in SQL Server:
CREATE TABLE BIKE_TWO (
SELECT VARCHAR(15),
TABLE INT);
The SQL code contains two reserved names; “SELECT” and “TABLE” that SQL Server will not allow. To fix this, you can place square brackets around them, and the code will run fine:
CREATE TABLE BIKE_TWO(
[SELECT] VARCHAR(15),
[TABLE] INT);
– Use Punctuation Marks the Right Way
Using punctuation the right way in SQL Server will prevent the “incorrect syntax near ‘.’. SQL Server stored procedure“. That’s because the server will understand your SQL queries and return a result (if applicable). For a start, have a look at the following SQL that we showed you earlier:
SELECT * FROM Customers WHERE Customers.FirstName = ‘O’Brien’
The customer’s first name has quotes that we used directly in the query, and this led to an error.
The fix is to use another punctuation mark before the “B” in Brien, and this will tell SQL Server that “O” and “Brien” are two separate words in quotes. This will allow it to parse the statement without throwing a syntax error.
SELECT * FROM Customers WHERE Customers.Name = ‘O”Brien’
Another example is the following SQL statement that we also showed you earlier, but we did not mention what caused the error. Observe the code for a second time, and you will see that we used quotes around a table name. This is wrong and that’s why the SQL Server shows a syntax error.
–This is wrong.
UPDATE Customers SET Lastname = ‘Doe’, ‘FirstName’ = ‘Janee’ WHERE CustomerID = 2;
The solution is to remove the quotes from the “FirstName” column, and this cements the concept of using punctuation marks the right way.
— This is correct
UPDATE Customers SET Lastname = ‘Gonzalez’, FirstName = ‘Jonathan’ WHERE CustomerID = 2;
– Use a Text Editor To Show the Unprintable Characters
Using a text editor is the ultimate tool to solve the “incorrect syntax near ‘ ‘. in C#” error when your code has no syntax error and yet, SQL Server says otherwise.
If you’re in such a situation, do the following:
- Download Notepad++ from their official website and install it on your computer.
- Open Notepad++, and click on “New file”
- Ensure the value of the “Encoding” menu is “Encode in UTF-8”. If it’s not there, set it.
- Copy your SQL statements that are failing in SQL Server, and paste them in Notepad++.
- Click the “Encoding” menu again, and change it to “Encode in ANSI”.
- Check your text again, and you’ll see the “invincible character”.
- Delete it, and run your code in SQL Server again. It should work.
Meanwhile, if you can’t get Notepad++, you can paste the SQL in an online tool like “SQLiteonline”, and you’ll see the invincible characters immediately.
Conclusion
This article explained the causes of the “incorrect syntax near” error in SQL Server, and five methods that can fix it for you, depending on your use case. From everything that we’ve talked about, and what you’ve learned so far, remember the following:
- Typographical errors and misuse of reserved keywords are the two major causes of the “incorrect syntax near” error in SQL Server.
- Misplaced punctuation marks and unprintable characters can also cause a syntax error in SQL Server.
- The top solution for the “incorrect syntax near” in SQL Server is to check for typographical errors, and use punctuation marks the right way.
- If all solutions fail to solve the incorrect syntax in your SQL statements, paste the SQL in Notepad++, and enable “Encoding in ANSI”.
Right now, the incorrect syntax should be resolved in your SQL code. Take care of yourself, and always run correct and valid SQL statements on your SQL server.
- Author
- Recent Posts
Your Go-To Resource for Learn & Build: CSS,JavaScript,HTML,PHP,C++ and MYSQL. Meet The Team
|
|