Update Accumulated Value with CTE error because of decimal datatype (SQL) - sql

I am trying to get the accumulated value of the column MontanteRecuperacao into montanterecuperacao_acumulada, by date and contract.
But the decimal datatype is becoming a problem and I don't know why, this works when the variables are of INT type.
This is the error message
Msg 4187, Level 16, State 1, Procedure spCalculaRecuperacao, Line 123
Data type decimal of receiving variable cannot store all values of the data type decimal of column 'montanterecuperacao_acumulada' without data loss.
Code:
DECLARE #MontanteRecuperacao_running DECIMAL,
#montanterecuperacao_acumulada_running DECIMAL,
#Contrato VARCHAR(10) = '' ;
WITH CTE AS
(
SELECT TOP 100 PERCENT
MontanteRecuperacao, montanterecuperacao_acumulada, ContratoId
FROM
MovimentoRecuperacao
ORDER BY
[ContratoId], [DtReferencia] DESC
)
UPDATE CTE
SET #montanterecuperacao_acumulada_running = montanterecuperacao_acumulada =
CASE
WHEN #Contrato <> ContratoId
THEN montanterecuperacao_acumulada
ELSE #montanterecuperacao_acumulada_running - #MontanteRecuperacao_running
END,
#MontanteRecuperacao_running = MontanteRecuperacao,
#Contrato = ContratoId

You've declared your DECIMAL parameters without specifying precision or scale:
#MontanteRecuperacao_running DECIMAL , #montanterecuperacao_acumulada_running DECIMAL
The default values are DECIMAL(18,0), which is essentially an integer. In order to get the behavior you desire, you'll need to assess your data for proper values to assign.

Related

How to convert from nchar to decimal in SQL?

I have 2 tables(source and destination) which are respectively NOR_LABOR and ALL_LABOR_DETAILS. In the source table(NOR_LABOR) there is a column "feet_produced" with the data type "nchar(10)". In the destination table(ALL_LABOR_DETAILS) there's a column "labor_feet_produced" with the data type "decimal(18,4)". I want to convert the "feet_produced" from nchar(10) to decimal(18,4) and paste it in the "ALL_LABOR_DETAILS" table's "labor_feet_produced" column.
I have found a code regarding a simillar issue but did not do the exact as I need to do, following is that code snippet :
Select feet_produced AS feet_produced_s, CASE WHEN Isnumeric(feet_produced) = 1
THEN CONVERT(DECIMAL(18,2),feet_produced)
ELSE 0 END AS feet_produced
INTO [MES_DEV].[dbo].[ALL_LABOR_DETAILS]
from [dbo].[NOR_LABOR]
Thank you!
There are values that will test true for IS_NUMERIC, but will fail to convert to decimal.
Instead, use TRY_CONVERT which will return either the successfully-converted-to-decimal value, or a NULL when it fails. (You can then COALESCE to zero to get your desired result).
Here is a short example set of values, using TRY_CONVERT:
SELECT
TryConvert = COALESCE(TRY_CONVERT(decimal(18,4),TestValues),0)
FROM (
VALUES('10.6'),
('ten'),
('7d2'),
('10000000000'),
('10.00000001')
) AS x(TestValues);
The same set of values using your example code will throw an error:
SELECT
IsNumericCase = CASE
WHEN Isnumeric(TestValues) = 1
THEN CONVERT(DECIMAL(18,2),TestValues)
ELSE 0
END
FROM (
VALUES('10.6'),
('ten'),
('7d2'),
('10000000000'),
('10.00000001')
) AS x(TestValues);
This error is returned because 7d2 is numeric, but cannot be converted to decimal.
Msg 8114, Level 16, State 5, Line 14
Error converting data type varchar to numeric.
Im not sure what the issue is with the code that dose not work for you.
But here is how I would do it with a small change in the statement that you just post it.
insert into[MES_DEV].[dbo].[ALL_LABOR_DETAILS](labor_feet_produced)
select CONVERT(DECIMAL(18, 4), feet_produced) AS feet_produced_s from[dbo].[NOR_LABOR]

SQL Sum function of a decimal column returns int instead of decimal

I have a column of decimal type and i need to use the sum function on it like this:
declare #credit decimal = (select
( select ISNULL(SUM(Convert(DECIMAL(13,2), Amount)),0)
from TransactionDetail as t1
where t1.AccountFrom = #fromAccount and t1.AccountTo = #toAccount
) -
( select ISNULL(SUM(Convert(DECIMAL(13,2),Amount)),0)
from TransactionDetail as t1
where t1.AccountFrom = #toAccount and t1.AccountTo = #fromAccount
)
)
select #credit
The output should be a decimal number like :
13.56
However, the result is always int, Any suggestions?
The default scale is 0. If you want the result as a particular format, try explicitly adding precision and scale to the variable:
declare #credit decimal(13, 2) = (select . . .
This behavior is well documented:
The number of decimal digits that will be stored to the right of the
decimal point. This number is substracted from p to determine the
maximum number of digits to the left of the decimal point. The maximum
number of decimal digits that can be stored to the right of the
decimal point. Scale must be a value from 0 through p. cSale can be
specified only if precision is specified. The default scale is 0;

SELECT Query - String or binary data would be truncated. The statement has been terminated

Query below gives the error above
SELECT * FROM dbo.DoSRF_001 ( 001 ,0 ,-1 ,0 ,'2014-01-01' )
Funny thing is, anything other than '2014-01-01' runs fine. Like '2015-01-01' or '2013-01-01'.
Function has hundreds of lines. But I thought it might have an easy solution.
Here are the parameters
CREATE FUNCTION [dbo].[DoSRF_001]
(
#FirmNo int = NULL
,#DeptNo int = NULL
,#SiteNo int = NULL
,#UnitNo int = NULL
,#PerdBeg datetime = NULL
)
I believe the "String or Binary data would be truncated" error is only producte when trying to INSERT or UPDATE data - I would check the places where you are actually updating a table and see what column values could have strings larger than the column width (e.g. if they're pulled from a different table).

Converting varchar to decimal removes digits

I made a SQL Server function that converts varchar to a decimal but it's removing digits and then returning a whole number.
Create FUNCTION [dbo].[ToMoney]
(
#Amount nvarchar
)
RETURNS decimal(14,2)
AS
BEGIN
-- Declare the return variable here
DECLARE #finalAmount as decimal(14,2);
IF Isnumeric(isnull(#amount, 0)) = 1
SET #finalAmount = CAST(#amount as decimal(14,2))
ELSE
SET #finalAmount = 0
-- Return the result of the function
RETURN #finalAmount;
END
When I run the following query:
SELECT dbo.ToMoney('123.45') as result
The result is '1.00'
I want it to return 123.45 as a decimal. What am I doing wrong?
The problem is your function definition. The use of nvarchar() with no length generally defaults in a length of 1.
Try this:
Create FUNCTION [dbo].[ToMoney]
(
#Amount nvarchar(255)
)
RETURNS decimal(14,2)
As a note: when it defaults to the length of 1, it is taking the first character in the string. That is why you are getting a value of 1.00.

select case statement error in mssql

SELECT top 1
case
when VR = -99999.99
then 0
else cast((VR*1.732) as decimal(38,3))
end
FROM pseb.dbo.datasource
where FeederID=5003
order by datetime desc
The above query is working fine, but I need to return varchar value '--' instead of returning 0
if I do like that
SELECT top 1
case
when VR = -99999.99
then '--'
else cast((VR*1.732) as decimal(38,3))
end
FROM pseb.dbo.datasource
where FeederID=5003
order by datetime desc
means it returns the following error:
Msg 8114, Level 16, State 5, Line 1 Error converting data type varchar
to numeric.
please help me to solve it
The problem is that you are returning two different data types from the same column. The rule with SQL Server that numeric types take precedence over string types, i.e. in a situation like yours a string gets converted to a number, not the other way around.
So to solve this you can cast your number to a string.
One option is to do something like this:
SELECT top 1
case when VR = -99999.99 then '--'
else
cast
(
cast((VR*1.732) as decimal(38,3)
)
as varchar(50))
end
FROM pseb.dbo.datasource where FeederID=5003 order by datetime desc