Sql Server using Convert and Replace together in the same statement - sql

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))

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]);

Error when a field is declared as NULL in where clause

We have a query running on sybase and we get the below error for certain account numbers but works for others
sqlanywhere error 1009145: Data type conversion not possible integer(10,0) to varchar(6,0)
(oselib/hos_dfe.cxx 13811)
So i started debugging it and found out the error was coming from a field in the format of an int( values are like 20,200,721). This field is declared as NULl in the where statment like FieldA is NULL.
So when i changed to STR(FieldA) it started to work and it all good now.
But my question is why would that cause the above error. Its an integer and the statement is only checking for values which are null and the values in the db are [NULL].
Any ideas why that is happening with this field?
This is NOT an integer: '10,000'. It is a string with digits and commas.
This is NOT an integer: '10000'. It is a string with just digits.
Sybase can only convert strings that are all digits to integers, and commas are not digits. (Okay, it can also handle leading negative signs too.) You can remove the commas using replace():
cast(replace(col, ',', '') as int)

SQL get decimal with only 2 places with no round

I have a query (SQL Server) that returns a decimal. I only need 2 decimals without rounding:
In the example above I would need to get: 3381.57
Any clue?
You could accomplish this via the ROUND() function using the length and precision parameters to truncate your value instead of actually rounding it :
SELECT ROUND(3381.5786, 2, 1)
The second parameter of 2 indicates that the value will be rounded to two decimal places and the third precision parameter will indicate if actual rounding or truncation is performed (non-zero values will truncate instead of round).
Example
You can see an interactive example of this in action here.
Another possibility is to use TRUNCATE:
SELECT 3381.5786, {fn TRUNCATE(3381.5786,2)};
LiveDemo
If you want to control the representation, you need to output the value as a string. One method is to convert to a decimal and then to a string:
select cast(cast(total as decimal(10, 2)) as varchar(255))
Another method is to convert to a string using str(). However, this often requires the removal of spaces:
select replace(str(total, 10, 2), ' ', '')

Conversion fails when trying to Convert string to int

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.

add zero and convert as varchar to a flot using a single query

I have data where I need to add leading zeros to it. But the problem is the data type is float. So whenever I add zeros, it automatically omits them. I have tried to add leading zero to it then try to convert it to varchar(50). But the it is giving an error:
Msg 102, Level 15, State 1, Line 1 Incorrect syntax near 'wallet_sys'.
I have used following query:
select (convert (varchar(50), ('0' + wallet_sys wallet_sys))) from NewSysData1
What have I done wrong?
PS: Some of the sample data are below: 17187383, 87339833, 93838793
I want these to be: 017187383, 087339833, 093838793
You have to add the zero after it's become a string, not before:
select '0' + convert (varchar(50), (wallet_sys)) as wallet_sys from NewSysData1
Normally, most people want to convert to having, say, a fixed width of result, with the appropriate number of leading zeros to make that happen. For that, it's a bit more work:
select RIGHT('0000000000' + convert (varchar(50), (wallet_sys wallet_sys)),10) as wallet_sys
from NewSysData1
Will produce 10 digits, with as many leading zeroes as needed (The number of zeroes in the string literal should be ~equal to the number of desired digits, and this is also the 10 provided at the right hand end of the first line)