我在sql server中进行了以下权重计算,即如果任何权重字段为NULL显示' NMI'否则加权。下面显示的所有权重字段都是nvarchar数据类型,例如[TIREWGHT],[WHLWGHT],[VALVEWGHT],[BOMPART1WGHT],[BOMPART2WGHT],[BOMPART3WGHT],[BOMPART4WGHT],[BOMPART5WGHT]
这是我想在计算中使用的条件
if ([BOM-TIRE] IS NOT NULL AND T1.[TIREWGHT] IS NULL) OR
([BOM-WHEEL] IS NOT NULL AND T1.[WHLWGHT] IS NULL ) OR
([BOM-VALVE] IS NOT NULL AND [VALVEWGHT] IS NULL) OR
([BOM-PART 1] IS NOT NULL AND [BOMPART1WGHT] IS NULL) OR
([BOM-PART 2] IS NOT NULL AND [BOMPART2WGHT] IS NULL) OR
([BOM-PART 3] IS NOT NULL AND [BOMPART3WGHT] IS NULL) OR
([BOM-PART 4] IS NOT NULL AND [BOMPART4WGHT] IS NULL) OR
([BOM-PART 5] IS NOT NULL AND [BOMPART5WGHT] IS NULL) then display `NMI`
otherwise [TIREWGHT]+[WHLWGHT]+[VALVEWGHT]+[BOMPART1WGHT]+[BOMPART2WGHT],[BOMPART3WGHT]+[BOMPART4WGHT]+[BOMPART5WGHT] .
注意:NMI
代表需要更多信息
我尝试了体重计算
UPDATE T1
SET [WGHT] = convert (float, T1.[TIREWGHT]) +
convert (float, T1.[WHLWGHT]) +
convert (float, T1.[VALVEWGHT]) +
convert (float, T1.[BOMPART1WGHT])+
convert (float, T1.[BOMPART2WGHT])+
convert (float, T1.[BOMPART3WGHT])+
convert (float, T1.[BOMPART4WGHT])+
convert (float, T1.[BOMPART5WGHT])
我尝试使用CASE
,但我得到了
错误转换错误
示例数据
[TIREWGHT] [WHLWGHT] [VALVEWGHT] [BOMPART1WGHT] [BOMPART2WGHT] [BOMPART3WGHT] [BOMPART5WGHT] [BOMPART5WGHT]
143 33 NULL 2.8 2.8 2.8 2.8 2.8
谢谢。
答案 0 :(得分:0)
听起来你的目标是在某些情况下同一列返回VARCHAR值(' NMI'),在其他情况下返回数值(或FLOAT)值。你不应该这样做。
相反,当一个或多个列包含空值时,创建第二列以返回NMI值。
根据您的具体需求,它可能看起来像这样:
SELECT [WGHT] = convert (DECIMAL(10,4), ISNULL(T1.[TIREWGHT],0)) +
convert (DECIMAL(10,4), ISNULL(T1.[WHLWGHT],0)) +
convert (DECIMAL(10,4), ISNULL(T1.[VALVEWGHT],0)) +
convert (DECIMAL(10,4), ISNULL(T1.[BOMPART1WGHT],0))+
convert (DECIMAL(10,4), ISNULL(T1.[BOMPART2WGHT],0))+
convert (DECIMAL(10,4), ISNULL(T1.[BOMPART3WGHT],0))+
convert (DECIMAL(10,4), ISNULL(T1.[BOMPART4WGHT],0))+
convert (DECIMAL(10,4), ISNULL(T1.[BOMPART5WGHT],0)),
[FulfillsCriteria] = CASE
WHEN TIREWGHT IS NULL OR
WHLWGHT IS NULL OR
VALVEWGHT IS NULL OR
BOMPART1WGHT IS NULL OR
BOMPART2WGHT IS NULL OR
BOMPART3WGHT IS NULL OR
BOMPART4WGHT IS NULL OR
BOMPART5WGHT IS NULL
THEN 'NMI'
ELSE '' END
答案 1 :(得分:0)
要将nvarchar转换为数字并将其保存在nvarchar字段中,请使用cast
示例:
declare @a NVARCHAR(100), @b NVARCHAR(100), @c NVARCHAR(100), @d NVARCHAR(100)
SET @a = '100'
SET @b = '200'
SET @c = NULL
Select @d = CAST(@a as float)+ CAST(@b as float)+ CAST(ISNULL(@c,0) as float);
select @d;
ISNULL
将处理您的NULL