|
|
Содержание
- Sql server varchar syntax error
- Вопрос
- Ответы
- Sql server varchar syntax error
- Answered by:
- Question
- Answers
- Sql server varchar syntax error
- Вопрос
- Ответы
- Все ответы
- SQLShack
- Common SQL syntax errors and how to resolve them
- SQL Keyword errors
- Arrangement of commands
- Using quotation marks
- Finding SQL syntax errors
- Related posts:
- About Milena Petrovic
Sql server varchar syntax error
Вопрос
I have a table(tab1) with a column(col1) of type varchar. I insert a row with an integer value(1). And when i query the table using the sql, select col1 from tab1 where col1 = 1, it works fine.
But after i insert a varchar, say ‘a‘ and then do the same query, i get an error message saying, «Syntax error converting the varchar value ‘a’ to a column of data type int.». Why is this so? Please reply.
Ответы
The problem is related to data conversion.
There are two categories of data type conversions:
- Implicit conversions are invisible to the user.
SQL Server automatically converts the data from one data type to another. For example, if a smallint is compared to an int, the smallint is implicitly converted to int before the comparison proceeds. Conversion from int to varchar() and varchar() to int is implicit.
When you run your query = 1 , SQL implicitly converts expected results to be integers . That’s why =’1′ will tell SQL not to implicitly convert 1 to int , but interpret it as string.
The table of conversion types can be foung in BOL «CAST and CONVERT».
Источник
Sql server varchar syntax error
This forum has migrated to Microsoft Q&A. Visit Microsoft Q&A to post new questions.
Answered by:
Question
I have a table(tab1) with a column(col1) of type varchar. I insert a row with an integer value(1). And when i query the table using the sql, select col1 from tab1 where col1 = 1, it works fine.
But after i insert a varchar, say ‘a‘ and then do the same query, i get an error message saying, «Syntax error converting the varchar value ‘a’ to a column of data type int.». Why is this so? Please reply.
Answers
The problem is related to data conversion.
There are two categories of data type conversions:
- Implicit conversions are invisible to the user.
SQL Server automatically converts the data from one data type to another. For example, if a smallint is compared to an int, the smallint is implicitly converted to int before the comparison proceeds. Conversion from int to varchar() and varchar() to int is implicit.
When you run your query = 1 , SQL implicitly converts expected results to be integers . That’s why =’1′ will tell SQL not to implicitly convert 1 to int , but interpret it as string.
The table of conversion types can be foung in BOL «CAST and CONVERT».
Источник
Sql server varchar syntax error
Вопрос
i have table with this feild
Deuration —————>Varchar Datatype
Duratio n
my taget is Multbly Duration $2 i use this code
i get this error (Syntax error converting the varchar value ‘:0’ to a column of data type int.)
i dont know wath is wrong with my code!
Ответы
The error in your code is you naïvely assume all data look the same. Apparently they done.
In any case, this is somewhat safer:
SELECT CASE WHEN isdate(Duration) = 1
THEN datediff(seconds, cast(’00:00:00′ AS time(0)),
cast(Duration as time(0)))
END AS Duration
FROM TBill
If you are on SQL 2005, use datetime, instead of time(0).
If you get NULL values in the output, these Duration values are malformed.
Erland Sommarskog, SQL Server MVP, esquel@sommarskog.se
If there is whitespace on either end of the Duration the len(Duration) <> 8 should return rows. So I assume you have some malformed Durations. Can you run the following.
. for example if you have a duration in a row of «123:0:23» then you get the error you described above. The above should help highlight such a row.
Likewise the following should filter them out.
/Neil Moorthy — Senior SQL Server DBA/Developer (MCITP (2005/2008), MCAD, ITILv3, OCA 11g) Please click the Mark as Answer button if a post solves your problem
Все ответы
Add rtrim to it like
select
(
(substring(rtrim(Duration),1,2) * 360) +
(substring(rtrim(Duration),4,2) * 60) +
(substring(rtrim(Duration),7,2))
)*2
AS Duration
from TBill
Many Thanks & Best Regards, Hua Min
You might use below:
| Blog: MSBICOE.com | MCITP — BI, SQL Developer & DBA
Hate to mislead others, if I’m wrong slap me. Thanks!
Using the sample durations you provide above it should not error, however can you confirm that you don’t have any [Durations] in the [TBill] table that are shorter or longer than expected (i.e. «1:00:23» or similar). If so you will need to deal with those, if they are padded with white-space then you can use Trim as suggested by Hua Min, if not you might have to use a case statement with LEN. Anyway can you run the following to check (you should get no results if all are 8 characters in length).
. you can also try adding «where len(duration) = 8» to your query above to see if the error dissapears.
/Neil Moorthy — Senior SQL Server DBA/Developer (MCITP (2005/2008), MCAD, ITILv3, OCA 11g) Please click the Mark as Answer button if a post solves your problem
Источник
SQLShack
Common SQL syntax errors and how to resolve them
In the SQL Server Management Studio, errors can be tracked down easily, using the built in Error List pane. This pane can be activated in the View menu, or by using shortcuts Ctrl+ and Ctrl+E
The Error List pane displays syntax and semantic errors found in the query editor. To navigate directly to the SQL syntax error in the script editor, double-click the corresponding error displayed in the Error List
SQL Keyword errors
SQL keyword errors occur when one of the words that the SQL query language reserves for its commands and clauses is misspelled. For example, writing “UPDTE” instead of “UPDATE” will produce this type of error
In this example, the keyword “TABLE” is misspelled:
As shown in the image above, not only the word “TBLE” is highlighted, but also the words around it. The image below shows that this simple mistake causes many highlighted words
In fact, there are total of 49 errors reported just because one keyword is misspelled
If the user wants to resolve all these reported errors, without finding the original one, what started as a simple typo, becomes a much bigger problem
It’s also possible that all SQL keywords are spelled correctly, but their arrangement is not in the correct order. For example, the statement “FROM Table_1 SELECT *” will report an SQL syntax error
Arrangement of commands
The wrong arrangement of keywords will certainly cause an error, but wrongly arranged commands may also be an issue
If the user, for example, is trying to create a new schema into an existing database, but first wants to check if there is already a schema with the same name, he would write the following command
However, even though each command is properly written, and is able to run separately without errors, in this form it results in an error
As the error message states, CREATE SCHEMA command has to be the first command that is given. The correct way of running this commands together looks like this
Using quotation marks
Another common error that occurs when writing SQL project is to use double quotation marks instead of single ones. Single quotation marks are used to delimit strings. For example, double quotation marks are used here instead of single ones, which cause an error
Replacing quotation marks with the proper ones, resolves the error
There are situations where double quotation marks need to be used, for writing some general quotes, for example
As shown in the previous example, this will cause an error. But, this doesn’t mean that double quotes can’t be used, they just have to be inside the single quotes. However, adding single quotes in this example won’t solve the problem, but it will cause another one
Since there is an apostrophe inside this quote, it is mistakenly used as the end of a string. Everything beyond is considered to be an error
To be able to use an apostrophe inside a string, it has to be “escaped”, so that it is not considered as a string delimiter. To “escape” an apostrophe, another apostrophe has to be used next to it, as it is shown below
Finding SQL syntax errors
Finding SQL syntax errors can be complicated, but there are some tips on how to make it a bit easier. Using the aforementioned Error List helps in a great way. It allows the user to check for errors while still writing the project, and avoid later searching through thousands lines of code
Another way to help, is to properly format the code
This can improve code readability, thus making the search for errors easier
Milena is a SQL Server professional with more than 20 years of experience in IT. She has started with computer programming in high school and continued at University.
She has been working with SQL Server since 2005 and has experience with SQL 2000 through SQL 2014.
Her favorite SQL Server topics are SQL Server disaster recovery, auditing, and performance monitoring.
- Using custom reports to improve performance reporting in SQL Server 2014 – running and modifying the reports — September 12, 2014
- Using custom reports to improve performance reporting in SQL Server 2014 – the basics — September 8, 2014
- Performance Dashboard Reports in SQL Server 2014 — July 29, 2014
About Milena Petrovic
Milena is a SQL Server professional with more than 20 years of experience in IT. She has started with computer programming in high school and continued at University. She has been working with SQL Server since 2005 and has experience with SQL 2000 through SQL 2014. Her favorite SQL Server topics are SQL Server disaster recovery, auditing, and performance monitoring. View all posts by Milena «Millie» Petrovic
Источник
В
реализациях языка SQL может
быть выполнено неявное преобразование
типов. Так, например, в Transact-SQL при
сравнении или комбинировании значений
типов smallint и int, данные типа smallint неявно
преобразуются к типу int. Подробно о явном
и неявном преобразовании типов в SQL
Server можно
прочитать в BOL.
Пример1:
Вывести среднюю цену портативных
компьютеров с предваряющим текстом
«средняя цена = ».
Попытка
выполнить запрос
-
SELECT
‘Средняя
цена
= ‘+AVG(price) -
FROMLaptop
приведет
к сообщению об ошибке:
Implicit
conversion from data type varchar to money is not allowed. Use the
CONVERT function to run this query.
(«Не
допускается
неявное
преобразование
типа
varchar к
типу
money. Используйте
для выполнения этого запроса
функцию CONVERT».)
Это
сообщение означает, что система не может
выполнить неявное преобразование типа
varchar к типу money. В подобных ситуациях
может помочь явное преобразование
типов. При этом, как указано в сообщении
об ошибке, можно воспользоваться
функцией CONVERT.
Однако эта функция не стандартизована,
поэтому в целях переносимости рекомендуется
использовать стандартное выражение CAST.
С него и начнем.
Итак,
если переписать наш запрос в виде
-
SELECT
‘Средняя
цена
= ‘+
CAST(AVG(price)
AS
CHAR(15)) -
FROM
Laptop
в
результате получим то, что требовалось:
Средняя
цена = 1003.33
Мы
использовали выражение явного
преобразования типов CAST для приведения
среднего значения цены к строковому
представлению.
Синтаксис
выражения CAST очень
простой
CAST(<выражение>
AS
<тип данных>)
Следует
иметь в виду, во-первых, что не любые
преобразования типов возможны (стандарт
содержит таблицу допустимых преобразований
типов данных). Во-вторых, результат
функции CAST для значения выражения,
равного NULL, тоже будет NULL.
Пример2: Определить
средний год спуска на воду кораблей из
таблицы Ships.
Запрос:
-
SELECT
AVG(launched) -
FROM
Ships;
даст
результат 1926. В принципе все правильно,
так как мы получили в результате то, что
просили — год. Однако среднее арифметическое
будет составлять примерно 1926,2381. Тут
следует напомнить, что агрегатные
функции (за исключением функции COUNT,
которая всегда возвращает целое число)
наследуют тип данных обрабатываемых
значений. Поскольку поле launched —
целочисленное, мы и получили среднее
значение с отброшенной дробной частью
(заметьте — не округленное).
А
если нас интересует результат с заданной
точностью, скажем, до двух десятичных
знаков? Применение выражения CAST к
среднему значению ничего не даст по
указанной выше причине. Действительно,
-
SELECT
CAST(AVG(launched)
AS
NUMERIC(6,2)) -
FROM
Ships;
вернет
значение 1926.00. Следовательно, CAST нужно
применить к аргументу агрегатной
функции:
-
SELECT
AVG(CAST(launched
AS
NUMERIC(6,2))) -
FROM
Ships;
Результат
— 1926.238095. Опять не то. Причина состоит
в том, что при вычислении среднего
значения было выполнено неявное
преобразование типа. Сделаем еще один
шаг:
-
SELECT
CAST(AVG(CAST(launched
AS
NUMERIC(6,2)))AS
NUMERIC(6,2)) -
FROM
Ships;
В
результате получим то, что нужно —
1926.24. Однако это решение выглядит очень
громоздко. Заставим неявное преобразование
типа поработать на нас:
-
SELECT
CAST(AVG(launched*1.0)
AS
NUMERIC(6,2)) -
FROM
Ships;
Аналогичные
преобразования типа можно выполнить с
помощью функции SQL Server CONVERT:
-
SELECT
CONVERT(NUMERIC(6,2),AVG(launched*1.0)) -
FROM
Ships;
Функция CONVERT имеет
следующий синтаксис:
CONVERT
(<тип_данных[(<длина>)]>,
<выражение> [,
<стиль>])
Основное
отличие функции CONVERT от
функции CAST состоит
в том, что первая позволяет форматировать
данные (например, темпоральные данные
типа datetime) при преобразовании их к
символьному типу и указывать формат
при обратном преобразовании. Разные
целочисленные значения необязательного
аргумента стиль соответствуют различным
типам форматов. Рассмотрим следующий
пример:
SELECT
CONVERT(char(25),
CONVERT(datetime,’20030722′));
Здесь
мы преобразуем строковое представление
даты к типу datetime, после чего выполняем
обратное преобразование, чтобы
продемонстрировать результат
форматирования. Поскольку значение
аргумента стиль не задано используется
значение по умолчанию (0 или 100). В
результате получим: Jul 22 2003 12:00AM
Ниже
приведены некоторые другие значения
аргумента стиль и результат, полученный
на приведенном выше примере. Заметим,
что увеличение значения стиль на 100
приводит к четырехзначному отображению
года.
1 |
07/22/03 |
11 |
03/07/22 |
3 |
22/07/03 |
121 |
2003-07-22 |
Есть
одна особенность использования
оператора CAST в
SQL Server, связанная с преобразованием
числа к его строковому представлению.
Что произойдет, если число символов в
числе превышает размер строки? Например,
SELECT
CAST(1234.6
AS
VARCHAR(5))
Следует
ожидать, что мы получим сообщение об
ошибке. Правильно,
вот
это
сообщение:
Arithmetic
overflow error converting numeric to data type varchar.
(«Ошибка
арифметического переполнения при
преобразовании числа к типу данных
VARCHAR».)
Естественно,
что мы будем ожидать того же сообщения
и при выполнении следующего оператора:
SELECT
CAST(123456
AS
VARCHAR(5))
Но
нет. В результате мы получим символ «*»
вместо сообщения об ошибке. Мы не беремся
судить, с чем это связано, однако, однажды
мы столкнулись с проблемой диагностики
ошибки в коде, в котором впоследствии
выполнялось обратное преобразование
к числовому типу.
В
нашем простейшем примере это будет
выглядеть так:
SELECT
CAST(CAST(123456
AS
VARCHAR(5))
AS
INT)
Вот
тут-то мы и получаем ошибку:
Syntax
error converting the varchar value ‘*’ to a column of data type int.
(«Ошибка
синтаксиса при преобразовании значения
«*» к типу данных INT».)
Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]
- #
- #
- #
- #
- #
- #
- #
- #
- #
- #
- #
Hi,
I want to convert a varchar datatype to int. The varchar column actually contains decimal values. for example
varchar Column
————-
36.00
20.00
35.00
60.00
….
…
I want it to be converted to
Int Column
———-
36
20
35
60
….
…
right now I was doing like this
cast((round(cast(qty as float),0)) as int). Is this a better way? If not please let me know the better way.
Thanks,
Sridhar!!
Farrell Keough
SSCoach
Points: 17414
I don’t see any problems with your code. You «may» not need round, if in fact your data just shows zeros in the decimal places. But otherwise it looks fine.
I have always used CONVERT. Is there an advantage to using CAST over CONVERT?
I wasn’t born stupid — I had to study.
Jeff Moden
SSC Guru
Points: 1002259
As Farrell suggested, you don’t need to do the rounding thing because INT will do the rounding for you.
Either of these will work…
SELECT CONVERT(INT,CONVERT(MONEY,'27.49')) SELECT CAST(CAST('26.50' AS MONEY) AS INT)
Obviously, you would substitute the column name for the string literal in both of the above statements.
Just a couple of side notes…
Although an intermediate conversion to float will certainly work in this case, you should be advised that FLOAT does it’s calculations based on Binary rather than Decimal numbering and the results will not always be what you would expect.
INT will round up at the .50 mark and round down at the .49 mark.
In case anyone else reads this, the reason two conversions are necessary is because the decimal point causes the following error when trying to convert a VARCHAR representation of a number with a decimal point in it, directly to INT.
SELECT CONVERT(INT,'27.49')
Server: Msg 245, Level 16, State 1, Line 1
Syntax error converting the varchar value '27.49' to a column of data type int.
Frank Kalis
SSC Guru
Points: 111183
January 10, 2005 at 2:37 am
#536610
Is there an advantage to using CAST over CONVERT?
CAST is the ANSI way of doing things. IIRC, even MS recommends this over CONVERT. Though only CONVERT allows for the style parameter for DATETIMES. I guess this is a case for the inconsequent category
—
Frank Kalis
Microsoft SQL Server MVP
Webmaster: http://www.insidesql.org/blogs
My blog: http://www.insidesql.org/blogs/frankkalis/[/url]
David Burrows
SSC Guru
Points: 65124
January 10, 2005 at 7:31 am
#536636
Or
SELECT CAST(FLOOR(Qty) AS int)
Far away is close at hand in the images of elsewhere.
Anon.