how to convert id datatype in sql server - sql

I have data like
id
27.45
29.1
27.45
21.95
18.1
51.75
0
21.45
41.94
21.95
32.95
My query is
SUM(CASE WHEN ab.dates BETWEEN bc.fst_sales_date AND BC.[WEEK4] THEN
[salesval] -- my initial try
ELSE 0 END) week4_qtyvalues
facing error
Conversion failed when converting the nvarchar value '41.94' to data
type int.
I have checked
SUM(CASE WHEN ab.dates BETWEEN bc.fst_sales_date AND BC.[WEEK4] THEN
CONVERT(float,[salesval]) -- this is what I've tried
ELSE 0 end) week4_qtyvalues
and
SUM(CASE WHEN ab.dates between bc.fst_sales_date AND BC.[WEEK4] THEN
CAST([salesval]AS int) -- this is what I've tried
ELSE 0 END) week4_qtyvalues
Regardless of my tries , I'm still facing the same error.

DECLARE #t TABLE (id VARCHAR(10))
INSERT INTO #t (id)
VALUES
('27.45'),('29.1'),('27.45'),('21.95'),('18.1'),
('51.75'),('0'),('21.45'),('41.94'),('21.95'),('32.95')
SELECT SUM(CASE WHEN id IS NOT NULL THEN CAST(id AS FLOAT) ELSE 0 END)
FROM #t

That is happening because you have a nvarchar and not a float number to cast to int. You should first cast the [salesval] to float and after that cast it to int. Something like this:
CAST(CAST([salesval] AS float) AS INT)

Because of the way SQL Server handles statements with multiple data types mixed together, it'll still try to take your salesval field and treat it as an int.
So, firstly, try casting the 0 as well.
And secondly, you almost certainly don't want to use float - it's for scientific calculations that need its huge range only and isn't precise. Try decimal instead.

Related

CAST, SUM, CASE Issues

I am trying to accommodate for some rogue values in my database, that contain the string 'unknown', I want to set these to 0 and then sum the rest. But for some reason, this isnt happening. Here is what I have -
Values - VARCHAR(30) -
3
0.1
2
16
2
5
2
Unknown
2.4
7
Unknown
And here is my Cast,Sum,Case
Cast(sum(case when stake = 'Unknown' then 0 else stake end) as float) as totalStake
But I get this error - Conversion failed when converting the varchar value '0.1' to data type int.
Help!
Thanks
You must cast stake as a float:
sum(case when stake = 'Unknown' then 0.0 else cast(stake as float) end) as totalStake
You should explicitly convert to some sort of numeric values. Try this:
sum(try_convert(numeric(18, 4), stake)) as totalStake
Your code has at least two issues. First, your case expression returns an integer (because the first then has an integer). So, it tries to convert stake to an integer, which can generate an error.
Second, you should be doing arithmetic operations on data that is explicitly some sort of number type and not rely on implicit conversion.
You can try the following query using isnumeric() to check numeric data.
create table temp (stake VARCHAR(30))
insert into temp values
('3'), ('0.1'), ('2'), ('16'), ('2'), ('5'), ('2'), ('Unknown'), ('2.4'), ('7'), ('Unknown')
--Select * from temp
Select sum(Cast(stake as Float)) from temp where isnumeric(stake) = 1
To handle some exception like null values or . values only you can try this
Select SUM(TRY_CAST(stake as Float)) from temp
You can find the live demo Here.
Initial step would be to replace the 'Unknown' string with 0 using a replace function and then convert the column datatype to the one which allows to perform Aggregate functions and then perform SUM on top of that. The below query will work only for 'unknown' string, if you have different strings other than 'unknown' you might have to choose a different approach like using IsNumeric in Replace function and update the string value to 0.
select sum(cast((REPLACE(stake,'unknown',0)) as float)) from table
This happens because SQL has some problems while converting decimal values to integer values.
In facts, function sum returns integer values
I solved it using round function on the values1 variable ( sorry for using same name for table and column ):
select Cast(sum(case when values1 = 'Unknown' then 0 else round(values1, 2) end) as
float)as totalstrike
from values1

Remove only zero after decimal sql server 2012

Consider the following numbers.
7870.2
8220.0
I need to remove decimal points if the value ends with .0. If it ends with .2 then it should keep the value as it is.
I have used ceiling but it removes all the values after decimal.
How can I write a select query in which I can add some condition for this?
Generally speaking you should not do this in your dB. This is an app or reporting side operation. The dB is made to store and query information. It is not made to format/string manipulate information.
use right within a case statement and:
DECLARE #val decimal(5,1)
SET #val = 7870.0
Select
Case
When right(#val,1)<> '0' then
cast(#val as varchar)
else
cast(cast(#val as int) as varchar)
End
output: 7870
EDIT: I could write :
Case
When right(#val,1)<> '0' then
#val
else
cast(#val as int) -- or floor(#val)
End
but because return type of case statement is the highest precedence type from the set of given types, so the output for second version is: 7870.0 not 7870, that's why I convert it to i.e varchar in when clauses, and it can be converted outside of case statement, I mean cast ((case when...then...else... end) as datatype)
Cast the number as a float, using float(24) to increase precision:
DECLARE #t table(number decimal(10,1))
INSERT #t values(7870.2),(8220.0)
SELECT cast(number as float(24))
FROM #t
Result:
7870,2
8220
Here below goes a sample:
declare #1 decimal(4,3)
select #1 = 2.9
select case when SUBSTRING (PARSENAME(#1,1), 1, 1) = 0 then FLOOR(#1) else #1 end
Change the #1 in the select statement with your database field name.
sqlfiddle
The solution seems to be simple:
SELECT CONVERT (FLOAT, PAYLOAD)

Conversion failed when converting the varchar value 645.00 to data type int

I am working on a SQL Query which performs some division operation on a column which is of type decimal(18,4) and should return a value of type decimal but for some reasons, It is giving me an error
Conversion failed when converting the varchar value 645.00 to data type int
I am not making any conversion to the value and yet I have no idea why that is trying to convert it to int.
My query part is as follows
CASE WHEN co.RequestID IS NOT NULL THEN cd.ConsDetQty/1000 WHEN nis.[867_key] IS NOT NULL
THEN q.Quantity/1000 ELSE q2.Quantity/1000 END AS 'Quantity'
May I know if I am wrong anywhere?
TRY THIS
CASE WHEN co.RequestID IS NOT NULL THEN CONVERT(DECIMAL(18,4),cd.ConsDetQty)/1000
WHEN nis.[867_key] IS NOT NULL THEN CONVERT(DECIMIAL(18,4),q.Quantity/1000
ELSE CONVERT(DECIMAL(18,4),q2.Quantity)/1000
END AS 'Quantity'
Your case statement is:
(CASE WHEN co.RequestID IS NOT NULL
THEN cd.ConsDetQty/1000
WHEN nis.[867_key] IS NOT NULL
THEN q.Quantity/1000
ELSE q2.Quantity/1000
END) AS Quantity
For this code to generate an error like that, cd.ConsDetQty, q.Quantity, or q2.Quantity is stored as a string rather than a number. You should fix the column, but you can quickly fix the query by doing:
(CASE WHEN co.RequestID IS NOT NULL
THEN cd.ConsDetQty/1000.0
WHEN nis.[867_key] IS NOT NULL
THEN q.Quantity/1000.0
ELSE q2.Quantity/1000.0
END) AS Quantity
That is a "quick-and-dirty" fix. I do not recommend having implicit conversions in real code. Better to do:
(CASE WHEN co.RequestID IS NOT NULL
THEN cast(cd.ConsDetQty as float)/1000.0
WHEN nis.[867_key] IS NOT NULL
THEN cast(q.Quantity as float)/1000.0
ELSE cast(q2.Quantity as float)/1000.0
END) AS Quantity

SQL Server : ignore strings in SUM function

I do a sum function over a column. But the column can have string values also. I want SQL Server to ignore the string values and sum only the string values.
Eg: column can have values like 16000Euro or 2588, or 3671.
The input is from user and I cant change validation in the app to integer
I have tried this but still shows error:
SUM(CASE WHEN Type_New = 202 AND ISNUMERIC(Summe) = 1
THEN Summe
ELSE 0
END) AS total_Euro
So how can I ignore the string values when doing sum operation?
The error I get is:
Error converting nvarchar value '2588. 'in the int data type.
EDIT: I want SQL to ignore such string values and sum what it can.. The main aim is that Query should not throw any error
Try the below Query, it will work perfectly :)
SELECT SUM(CASE WHEN Type_New = 202 AND ISNUMERIC(Summe + '.0e0') = 1
THEN Summe
ELSE 0
END) AS total_Euro FROM TableName
IsNumeric returns 1 if the varchar value can be converted to ANY number type (includes int, bigint, decimal, numeric, real & float) Values like 1e4,1., 2.0 will create the issue if the above check to bypass these values is not added.
You should not name column same as a keyword in SQL Server , if this cannot be avoided you can escape column name by enclosing in square bracketes [Sum] as shown below
SELECT SUM(CASE WHEN Type = 202 AND ISNUMERIC([Sum]) = 1 THEN [Sum] ELSE 0 END) AS total_Euro
Try this
SUM(CASE WHEN Type = 202 AND case when Sum not like '%[^0-9]%' THEN Sum END ELSE 0 END) AS total_Euro
or
SUM(CASE WHEN Type = 202 AND ISNUMERIC(Sum+'.e0') = 1 THEN Sum ELSE 0 END) AS total_Euro
Try this:
SUM (CASE
WHEN Type_New = 202 AND ISNUMERIC(Summe) = 1 THEN CAST(summe AS DECIMAL(9,2))
ELSE 0 END) AS TotalEuro
I don't know if you do this SUM for one column or what, but also you can filter out what you need and then sum:
SELECT SUM(Summe) AS total_Euro
FROM someTable
WHERE Type_New = 202 AND ISNUMERIC(Summe) = 1
ISNUMERIC function considers strings that contain large numeric (e.g., 9223372036854775808), decimals (e.g., 12.4), currency figures (e.g., $123), and floating-point values (e.g., 1E2) to be strings that can be converted to a numeric data type.
Now to calculate Sum you will have to convert string to an integer[ this assumption is based on
sample data you have posted] but fact is string can be numeric but might not be convertible to an integer; the ISNUMERIC function is limited in the sense that it can tell you only whether the string can be converted to any numeric data type.
So if your column doesn't have string data like 1E3 or 12.4 or $123 which are numeric but not integers you can simply cast the target column to int as below and calculate the sum :
select SUM(CASE WHEN Type_New = 202 AND ISNUMERIC(Summe) = 1
THEN CAST(Summe AS INT)
ELSE 0
END) AS total_Euro
FROM test
else you shoudl go for a more generic function which as discussed here..
http://sqlmag.com/t-sql/can-i-convert-string-integer

Error in Converting nvarchar to int

I have one table #DateDay_temp in which there is a column ExtraAdultPrice of type NVARCHAR(20). When I am trying to run this statement in a stored procedure
DECLARE #ExtraAdultPAX DECIMAL(10,2)
SELECT
#ExtraAdultPAX = SUM(CAST((CASE ISNULL(ExtraAdultPrice, '')
WHEN '' THEN 0
ELSE ExtraAdultPrice END) AS DECIMAL(10,2)))
FROM #DateDay_temp;
When I am passing the value 54.56 in the ExtraAdultPrice" column, I get the error
Conversion failed when converting the nvarchar value '54.56' to data
type int.
Help would be appreciated.
Most likely this error happens because of the fact you have a 0 in your CASE statement; therefore, the "type" of the CASE statement is decided to be an INT - which is completely wrong here....
Try this instead:
SELECT
#ExtraAdultPAX = SUM(CAST((CASE ISNULL(ExtraAdultPrice, '')
WHEN '' THEN 0.00 <<== use "0.00" instead of just "0" !!
ELSE ExtraAdultPrice
END) AS DECIMAL(10,2)))
FROM
#DateDay_temp;
Now, everything should be DECIMAL(10,2) and there shouldn't be any attempt to convert your values to an INT
54.56 isn't an int because of the decimal point.