SQL Multiplication - Update Query
SQL 2008 - Simple Query logic.
In my Table :TableName, i have 3 columns [Ship Qty], Size, Qty.
Default value for Qty is NULL. I wrote an Update Query to update the column : Qty. I need to multiply [Ship Qty] * Size.
Column : Size is nvarchar. It carries two conditons
1) If the value is 60 EA or 3 ML, I need to consider only 60 or 3 or 3.5 ...
2) If the value is 60X3 ML, I need to consider 60X3 which is 180. Th开发者_如何学Cen, this multiplied value will be multiplied with [Ship Qty].
update [TableName]
set Qty = [Ship Qty] * CONVERT(INT, (Size)) * CONVERT(Float, (Size))
WHERE Size > 0
AND Size > 0
AND Qty IS NULL
Ship Qty Size Qty
1 100 EA 100
3 60 EA 180
2 60X3ML 360
In the above table, Column : Qty is updated through SQL Query. My Query throws exception.
Bad/odd design but for what hopefully a one-off fix;
;with TEST ([Ship Qty], Size) as (
select 1,'100 EA' union all
select 3,'60 EA' union all
select 2,'60X3ML' union all
select 2,'60X2ML' union all
select 2,'60' union all
select 2,'1 X3PP'
)
select
[Ship Qty],
Size,
[Ship Qty] * (
cast(substring(Size, 1, patindex('%[^0-9]%', Size + '/') - 1) as int)
*
case when charindex('X', Size, 1) > 0 then
cast(substring(substring(Size, charindex('X', Size) + 1, len(Size)), 1, patindex('%[^0-9]%', substring(Size, charindex('X', Size) + 1, len(Size)) + '/') - 1) as int)
else
1
end
)
from TEST
For
Ship Qty Size (No column name)
1 100 EA 100
3 60 EA 180
2 60X3ML 360
2 60X2ML 240
2 60 120
2 1 X3PP 6
You have several problems:
- First: It seems to me that your multiplication may return a float and yet your QTY column looks like is defined as an integer
- Second (definitely an issue): You are converting the Size column, which has strings to a float. How do you expect that to work?
- Third: Why do you have two QTY columns in your example data? Where's the Ship QTY Column you refer to?
精彩评论