Reputation:
The following query attempts to convert a varchar
datatype to int
-- but it's not working. Do you know why?
SELECT
CONVERT(INT, [BR]) AS dd,
CAST([BR] AS INT) AS cc
FROM
[Seg].[dbo].[pro_ben]
I get the error:
Msg 245, Level 16, State 1, Line 2
Conversion failed when converting the varchar value '3893.768' to data type int
Upvotes: 0
Views: 3684
Reputation: 153
I would try
Select Round([BR],0) as dd
FROM [Seg].[dbo].[pro_ben];
Upvotes: 0
Reputation: 1271003
The value is not an integer. This leaves you with various options:
try_convert()
which would return NULL
.numeric()
instead.Conversion to a numeric
ignores decimal points, but they do not cause an error:
SELECT convert(numeric(10,0), [BR]) as dd
FROM [Seg].[dbo].[pro_ben];
You can then convert to an int
if you specifically need that type.
Upvotes: 1
Reputation: 222672
Obviously your string has a decimal part, hence you cannot cast it directly to an integer.
A solution would be to first CAST
to a floating point number, and then to an integer, like:
SELECT CAST( CAST([BR] AS FLOAT) AS INT) AS CC FROM [Seg].[dbo].[pro_ben]
SELECT CAST('3893.768' AS FLOAT)
| (No column name) | | ---------------: | | 3893.768 |
SELECT CAST( CAST('3893.768' AS FLOAT) AS INT)
| (No column name) | | ---------------: | | 3893 |
Upvotes: 3