Conversion fails when trying to Convert string to int - sql

I have some sales numbers in a string column that I need to convert to some format so that i can calculate them with each other but I get this error while trying to convert them.
Conversion failed when converting the varchar value '-6.353,35' to data type int.
I'm not allowed to lose any money by rounding it up. It doesnt mather but in what type i convert as long as im not rounding them up. What's your thoughts?
For example i have -6.353,35 and 300,30 and i want to sum them too -6.053,05

try this...
select convert(int,convert(float,replace('-6.353,35',',','')))
as there are (,) Commas it cannot be converted to float,so remove the (,)commas after converting to float we can convert to int
If you want decimal values, then you should use float
select convert(float,replace('-6.353,35',',',''))
Edit
Like #marc_s suggested, it is preferred to use decimal rather than float
select convert(decimal,replace('-6.353,35',',',''))

Firstly, you want to convert this to a decimal value, not an int, as you will lose anything after decimal point otherwise.
The problem here is the separators that are being used when storing your values.
With your numbers, you have points . to represent thousand separators and commas , to represent decimal points.
To enable you to convert the value to a valid decimal you need to have it in a format that SQL Server can process.
A simple way to do this would be to remove/replace the problem characters before trying to convert the value:
DECLARE #val AS VARCHAR(10) = '-6.353,35'
-- step 1: remove thousand separator
SET #val = REPLACE(#val, '.', '')
SELECT #val AS RemoveThousandSeparator
-- step 2: replace decimal separator with decimal point
SET #val = REPLACE(#val, ',', '.')
SELECT CONVERT(DECIMAL(18,2), #val) AS DecimalPointAdded
-- to do it in one statement:
SET #val = '-6.353,35'
SELECT CONVERT(DECIMAL(18,2),
REPLACE(REPLACE(#val, '.', ''), ',', '.')) AS NumericeRepresentation
Aside from this, you would be much better off storing numeric values in the correct format in the first place to avoid this kind of workaround.

Related

Remove all trailing decimal points from a number stored as a string

I have a couple of strings (nvarchar data type), one is a whole number and one has decimal points trailing. My goal is to remove decimals and have all values as a whole number.
I tried the code below but it gives me an error for the value with no decimals. Is there a way to accomplish this without a case expression. I'll be using this new column in a join.
SELECT [SOW]
--,LEFT([SOW], CHARINDEX('.', [SOW])-1) as 'TestColumn'
FROM [dbo].[t_Schedule_kdm]
WHERE sow in ('15229.11','11092')
Output:
11092
15229.11
My desired Output:
11092
15229
Just append a dot character so that you'll always find an index:
LEFT(SOW, CHARINDEX('.', SOW + '.') - 1)
It's not clear whether you need to cast the result of that expression to an integer value.
Convert first to the most precision number you could ever have e.g. decimal(9,2) then convert to an int. You can't convert directly from a decimal string to an int.
SELECT [Value]
, CONVERT(int,CONVERT(decimal(9,2),[Value]))
FROM (
VALUES ('15229.11'),('11092')
) x ([Value]);

Sql Server using Convert and Replace together in the same statement

I wanted to double check my logic for a query in SQL Server.
The idea is that I am able to feed the following values and it will make sure the result is a decimal with four trailing digits.
Possible values for #LABORQTY:
1,200
1,200.42
1200 (Integer)
1200.42
1200 (As a String)
1200.42 (As a String)
When the value is a string, it will give the error:
Error converting data type nvarchar to numeric.
Here is my code:
CONVERT(DECIMAL(12, 4), REPLACE(#LABORQTY, ',', ''))
The output each time though should be decimal:
1200.4200
Your question is really confused, but I'll answer according to the following parameters:
#laborqty is a VARCHAR
#laborqty may somehow come to contain any of the following values:
'1200'
'1200.42'
'1,200'
'1,200.42'
In which case CONVERT(DECIMAL(12, 4), REPLACE(#LABORQTY, ',', '')) will indeed produce a decimal with up to 4 digits of fractional precision. Whether your query tool/programming language will output it as 1200.4200 or not is another matter entirely; it might well just output 1200.42 and drop the trailing zeroes
If you're getting Error converting data type varchar to numeric. still, there is some other character data (not comma) in your numeric string
If you definitely want the trailing zeroes, format it into a string before you output
FORMAT(CONVERT(decimal(12,4), '1200.42'), '0.0000')
This will generate a string with 4 trailing zeroes
you can use :
select CAST ( REPLACE( '1,200.4' , ',','') AS decimal(17,4))

T-SQL - CAST char with leading zeros to int

I'd like to convert char with leading zeros to int, ex '00010' to 00010. I've tried to use CAST or CONVERT :
select CONVERT(int, '00010')
but the function removes zeros at the beginning and return 10 instead of 00010.
Do you know any easy solution to this? The length of input will be allways 5.
Mathematically, leading zeros are meaningless, so an Int can't have leading zeros.
If you need to display leading zeroes, you can always convert to varchar and use concatenation with right, like this:
DECLARE #MyVal int = 10;
SELECT RIGHT('00000' + CAST(#MyVal as varchar(5)), 5)
You must read about data types. An INT is noting more than a bit pattern. Whenever you see the number in a human readable format, the actual value is translated to a string consisting of digits. But this digit format is not the actual INT.
Leading Zeros are never part of the INT itself, but may be added to the string representation. So your question (taken literally) does not make any sense actually.
If there is a string like 00012 and you want to use it like a number, you should just cast it:
SELECT CAST('00012' AS INT) + 2; --14
Other answers show you some approaches to get a padded string representation out of an INT, but this is the opposite direction:
SELECT REPLACE((STR(12,5),' ','0'); --00012
You can combine these approaches:
DECLARE #PaddedNumber CHAR(5)='00012'
SELECT REPLACE(STR(CAST(#PaddedNumber AS INT) + 2,5),' ','0'); --00014
The padded number (which is - by type! - a string) is casted to an INT, then used in computation. The result is an INT, which can be converted to a padded string. But the final result's type is string...
SELECT FORMAT(CONVERT(INT,'00010'), 'd5')
should solve the problem :)

how to convert different datatypes to int in sql

I have a nvarchar(200) column in a table that contains a mix of integers (as strings) and non-integer strings and symbols also. E.g. Some sample data :-
Excuse me for my typing in my initial post I mentioned varchar(200) but in fact it is 'nvarchar(200)'
02
0
.../
125
00125
/2009
1000
0002589
000.00125
Marathi numbers like & letters
how can I order this Column?
You can use CAST to convert a varchar to an INT given that varchar is holding a proper number.
SELECT CAST(varCharCol as Int)
E.g.
col1 as Varchar(10)
col1 = '100' converting to INT will be successufl
but if col1 = '100 xyz' will be unsucessful in the process.
Looking at your string you may have to use number of LTRIM, REPLACE to get hold of the digits or using a regex to get comma separated numbers. That too it's not very clear how your original string looks like.
References.
Many DBMS have CAST() functions where you can convert one datatype to another.
For MySQL have a look at this site
You can Use CAST and Convert to convert string type value to int type. but be sure the value should numeric.
select convert(int,'123')
select CAST('123' as int)
You can use this query
SELECT CASE
WHEN ISNUMERIC(colName)=1 THEN ROUND(colName, 0)
ELSE 0 END AS [colName]
FROM tblName

SQL Server CONVERT(NUMERIC(18,0), '') fails but CONVERT(INT, '') succeeds?

PRINT CONVERT(NUMERIC(18,0), '')
produces Error converting data type varchar to numeric.
However,
PRINT CONVERT(INT, '')
produces 0 without error...
Question: Is there some SQL Server flag for this or will I need to do case statements for every varchar to numeric conversion? (aside from the obvious why?)
Use ISNUMERIC
declare #a varchar(20)
set #a = 'notanumber'
select case when isnumeric(#a) = 0 then 0 else convert(numeric(18,0),#a) end
ISNUMERIC doesn't alway work as you might expect: in particular it returns True for some values that can't subsequently be converted to numeric.
This article describes the issue and suggests how to work around it with UDFs.
Empty string will convert to zero for float and int types, but not decimal. (And converts to 01 Jan 1900 for datetimes = zero). I don't know why.. it just is...
If you need decimal(18,0), use bigint instead. Or cast via float first
ISNUMERIC will accept - and . and 1.2E3 as a number, but all fail to convert to decimal.