SQL Server Arithmetic overflow error converting expression to data type int - sql

I have a trigger which executes after a record is inserted into a table. The trigger basically, calls a function and passes values from the insert into it. However, while it works some times, I also keep getting the following error:
Msg 8115, Level 16, State 2, Procedure UpdateNabersRating, Line 17
Arithmetic overflow error converting expression to data type int.
The trigger is as follows:
UPDATE BMS_Snapshot SET
NABERS = dbo.SetmetricsNABERSCalculation(
60,
tbl.NetFloorArea,
tbl.ElectricityCumulative,
tbl.GasCumulative,
tbl.ElectricityCumulativeMax,
tbl.GasCumulativeMax,
tbl.ElectricityMaxTotal,
tbl.GasMaxTotal,
tbl.NaturalGasConversionCubicMetersToMJ,
tbl.SuburbId)
FROM
(SELECT
Snap.SnapshotId AS SnapshotId,
Snap.ElectricityCumulative AS ElectricityCumulative,
Snap.GasCumulative AS GasCumulative,
Building.NetFloorArea AS NetFloorArea,
Building.NABERSElecTotalMax AS ElectricityMaxTotal,
Building.NABERSGasTotalMax AS GasMaxTotal,
Building.NABERSExpiry As Expiry,
NABERSTarget.ElecCumulativeMax AS ElectricityCumulativeMax,
NABERSTarget.GasCumulativeMax AS GasCumulativeMax,
[State].NaturalGasConversionCubicMetersToMJ AS NaturalGasConversionCubicMetersToMJ,
Suburb.SuburbId AS SuburbId
FROM inserted AS Snap
INNER JOIN AST_Building AS Building ON Snap.BuildingId = Building.BuildingId
INNER JOIN ESD_Suburb AS Suburb ON Building.SuburbId = Suburb.SuburbId
INNER JOIN ESD_State AS [State] ON Suburb.StateId = [State].StateId
INNER JOIN AST_NABERSTarget NABERSTarget ON Snap.BuildingId = NABERSTarget.BuildingId AND
Snap.TimeStamp = NABERSTarget.Timestamp
/*Where Snap.SnapshotId IN (Select inserted.SnapshotId FROM inserted)*/) AS tbl
WHERE tbl.SnapshotId = BMS_Snapshot.SnapshotId AND BMS_Snapshot.Range = 1
I've been playing around with it for a while, but can't seem to put my finger on the problem, particularly given it works sometimes.

Changed, arguments on function to FLOAT, instead of INT for two of the parameters.

Related

SQL Server : merge using Join on Source Table fails to bind

I am writing a SQL Server Merge statement but can't seem to get the syntax correct. Would someone please take a look to see where I'm going wrong?
Any help you can give is most appreciated.
What I have is two tables that I'd like to merge (w_materialmarketprices2 and d_component). My source (d_component) table requires me to do a join to a tax table (d_tax).
Everything works fine except for when I try to add the additional tax table into my join. The reason I need the tax table is because it contains a tax rate which I don't have in my d_component table (although I do have the corresponding tax code).
My comparison criteria between w_materialmarketprices2 and d_component includes the tax rate in the calculation.
Here's my code:
MERGE [DWH].[dbo].[w_materialmarketprices2] AS A
USING
(SELECT
[comp_code], [comp_desc], [comp_o_un], [comp_type],
[comp_ccy], [comp_tx], [comp_net_price], [comp_per],
[comp_doc_date], [comp_last_update], [comp_latest],
D.[tax_rate] AS TaxRate
FROM
[DWH].[dbo].[d_component]) AS B
INNER JOIN
[DWH].[dbo].[d_tax] AS D ON D.[tax_code] = B.[comp_tx]
ON
A.[mp_comp_code] = B.[comp_code] AND A.[mp_valid_date] = B.[comp_doc_date] AND B.[comp_net_price]>0 AND A.[mp_price_inc_vat] = ROUND(((B.[comp_net_price]/B.[comp_per])*(1+TaxRate),3) AND A.[mp_budget_actual] = 'PO Actual' AND B.[comp_type] ='P100' AND (left(B.[comp_code],1)='S' OR left(B.[comp_code],1)='R')
WHEN NOT MATCHED BY TARGET
THEN
INSERT ([mp_budget_actual], [mp_comp_code], [mp_comp_desc], [mp_unit], [mp_unit_qty], [mp_qualified_supplier], [mp_ccy], [mp_price_inc_vat], [mp_valid_date], [mp_last_update], [mp_latest])
VALUES ('PO Actual', B.[comp_code], B.[comp_desc], B.[comp_o_un], 1, 'Y', B.[comp_ccy], ROUND(((B.[comp_net_price]/B.[comp_per])*(1+TaxRate),3), B.[comp_doc_date], B.[comp_last_update], B.[comp_latest])
;
The error I'm getting is:
Msg 4145, Level 15, State 1, Line 20
An expression of non-boolean type specified in a context where a condition is expected, near ','.
Msg 102, Level 15, State 1, Line 23
Incorrect syntax near 'B'.
,D.[tax_rate] AS TaxRate shows up as underlined in red so I reckon the problem is something to do with that. I also get the message
The multi-part identifier "D.tax_rate" could not be bound
Thanks for your help in advance. Honkonger.
There is no reason to use a subquery in the USING clause, ie: don't put a SELECT in there:
MERGE [DWH].[dbo].[w_materialmarketprices2] AS A
USING
[DWH].[dbo].[d_component] AS B
INNER JOIN [DWH].[dbo].[d_tax] AS D ON D.[tax_code] = B.[comp_tx]
ON
A.[mp_comp_code] = B.[comp_code] .......

How to Join (equal) two data columns that belongs to the String and Double types respectively in Alibaba MaxCompute?

I am not authorized to share the table details.
For instance, let me consider an Example:
I am trying to join two columns of String and Double data types respectively in Alibaba MaxCompute.
In the earlier version of MaxCompute, the String and Double data types are converted to the bigint data type at the cost of precision. 1.1 = “1” in a Join condition.
Whereas the same code does not work in the new version of the MaxCompute. The code syntax is like follows:
SELECT * FROM t1 JOIN t2 ON t1.double_value = t2.string_value;
Error:
WARNING:[1,48] implicit conversion from STRING to DOUBLE, potential data loss, use CAST function to suppress
What is the correct syntax to do the join operation in Alibaba MaxCompute V2?
I did a bit of digging and it seems like this SQL command is the recommended way of getting around this issue.
select * from t1 join t2 on t.double_value = cast(t2.string_value as double);
As the error message suggests:
SELECT *
FROM t1 JOIN
t2
ON CAST(t1.double_value as string) = t2.string_value;

Error converting data type varchar to bigint. when using update

I'm using SQL Server. I'm trying to run the following SQL script and I'm getting this error:
Error converting data type varchar to bigint.
This is the script:
with T as
(
select
sp.ProfileId
,sp.ProfileHandle
,sp.[Description]
from
[SocialProfile] sp
inner join
Entity e on sp.EntityId = e.EntityId
where
e.EntityStatusId != 3 and e.EntityStatusId != 4
and sp.SocialProfileTypeId in (1, 2, 10)
and (ISNUMERIC(sp.ProfileHandle) = 1)
and IsRemoved = 0
)
update T
set ProfileHandle = NULL
where ProfileHandle = ProfileId
I tried to use cast function but it doesn't work. Can someone tell me what I'm doing wrong?
The isnumeric() doesn't give the protection you want. Use try_convert() for the comparison:
with T as (
select sp.ProfileId, sp.ProfileHandle, sp.[Description]
from [SocialProfile] sp inner join
Entity e
on sp.EntityId = e.EntityId
where e.EntityStatusId not in (3, 4) and
sp.SocialProfileTypeId in (1, 2, 10) and
ISNUMERIC(sp.ProfileHandle) = 1 and -- you can leave it in
IsRemoved = 0
)
update T
set ProfileHandle = NULL
where try_convert(int, ProfileHandle) = ProfileId;
SQL Server has a "feature" where it will rearrange the conditions in the query. The CTE does not get executed "first", so the isnumeric() is not necessarily run before the conversion in the where. I consider this a bug. Microsoft considers this a feature (because it provides more options for optimization).
The only ordering guaranteed in a query is through case expressions. The simplest work-around is try_convert().
In addition, I strongly recommend never relying on implicit conversions. Always explicitly convert. I have spent many hours debugging code for problems caused by implicit conversion.

SQl - An expression of non-boolean type specified in a context where a condition is expected, near ')'

Getting this error with the following query in SQL Server 2014.
SELECT
[Case]
,[Course]
,[Device]
,[IntegerValue]
,[Question]
,IFL.[QuestionSimplified]
,[Revision]
,[Script]
,[TextValue]
,[Timestamp]
,[Type]
,[Variable]
,[Wave]
FROM [dbo].[CosmosData] CD
Left Outer join [dbo].[ImportedFacilityList] IFL on CD.[Variable] = IFL.[Variablename]
where
CD.[Script] = 'CARD-F' and
(select * from [dbo].[CosmosData] where Variable = 'SURVEY_TYPE' and IntegerValue = '2')
When I run the above query I am getting the beloiw error,
Msg 4145, Level 15, State 1, Line 20
An expression of non-boolean type specified in a context where a condition is expected, near ')'.
Any help please?
You have this in the where clause:
and (select * from [dbo].[CosmosData] where Variable = 'SURVEY_TYPE' and IntegerValue = '2')
SQL needs a boolean expression. This is usually formed by using = or a similar comparison operator. In your case, I think you just exant exists:
exists (select * from [dbo].[CosmosData] where Variable = 'SURVEY_TYPE' and IntegerValue = 2)
That said, you might want a correlation clause as well.
Note: I removed the single quotes from the integer value. Only use single quotes for string and date constants.
based on the assumption that you are using case as a key in this table, you can use the follwing to return all rows from cosmos data where your conditions are applied and the select in your where clause has a match using the criteria within it.
SELECT
[Case]
,[Course]
,[Device]
,[IntegerValue]
,[Question]
,IFL.[QuestionSimplified]
,[Revision]
,[Script]
,[TextValue]
,[Timestamp]
,[Type]
,[Variable]
,[Wave]
FROM [dbo].[CosmosData] CD
Left Outer join [dbo].[ImportedFacilityList] IFL on CD.[Variable] = IFL. [Variablename]
where CD.[Script] = 'CARD-F'
and Case
IN
(select Case from [dbo].[CosmosData] where Variable = 'SURVEY_TYPE' and IntegerValue = '2')
Hope that helps any

SQL Server 403 Error When Setting a Geography Type for Update

All I need to do is simply get one geography value from a table and store it in another table. There is some logic for which row to take from the origin table so it's not just a straight select.
In any of 50 possible variants of this, I get this error when hitting the update to the target table:
Msg 403, Level 16, State 1, Line 1
Invalid operator for data type. Operator equals not equal to, type equals geography.
My SQL looks like this at the moment:
declare
#EquipmentId int
, #CurrentLocationId int
, #CurrentGeoLocation geography
, #LastUpdated datetime
select #EquipmentId =
(
select top 1 EquipmentId
from Equipment
order by EquipmentId
)
select #CurrentLocationId = (select top 1 EquipmentLocationId from EquipmentLocation where EquipmentId = #EquipmentId order by LastUpdated desc)
select #LastUpdated = (select top 1 LastUpdated from EquipmentLocation where EquipmentId = #EquipmentId order by LastUpdated desc)
UPDATE
dbo.Equipment
SET
CurrentLocationDateTime = #LastUpdated
, CurrentGeoLocation = (select GeoLocation from EquipmentLocation where EquipmentLocationId = #CurrentLocationId)
, ModifiedBy = 'system'
, ModifiedByUserId = -1
, ModifiedDate = getdate()
WHERE
EquipmentId = #EquipmentId
I have had CurrentGeoLocation set in a variable of the same type, selected into by the same statement you see in the update.
I have had an #CurrentGeoLocation variable populated by a geography::STGeomFromText as well as geography::Point() function call.
I've used Lat and Long variables to call Point and FromText functions.
All the same result, the above 403 error. I could understand it somewhat when I was concatenating various permutations of the GeomFromText function that needs well known text format for the point parameter, but field value to field value is killing me, as is the fact that I get this error no matter how I try to give the origin point data to the target table.
Thoughts?
Update:
I've been experimenting a little and found that the following works just fine:
declare #GL geography
select #GL = (select GeoLocation from EquipmentLocation where EquipmentLocationId = 25482766)
print convert(varchar, #GL.Lat)
print convert(varchar, #GL.Long)
update Equipment set CurrentGeoLocation = geography::Point(#GL.Lat, #GL.Long, 4326)-- #NewGL where EquipmentId = 10518
But then when I apply this plan to the original script, I'm back to the same error.
The data in the test is working off the exact same records as in the original script. The original script is working off a collection of EquipmentIds, on the first one, I encounter this problem. The short test script uses the same EquipmentLocationId and EquipemntId that are the selected values used to update the first Equipment record in my collection.
Solved!
The error had nothing to do with the geography type as SQL reported. By pulling items in and out of the update statement in an effort to isolate why I still get the error even if I save everything but CurrentGeoLocation and then another update for the geography, I found that CurrentLocationDateTime (datetime, null) was the culprit. Deleted the column, added it back. Problem solved. Original script works as expected.
Don't know what happened to that datetime column that caused it to throw errors against a geometry type, but it's fixed.