如何在SELECT语句中构造IF语句?

时间:2014-04-14 15:42:03

标签: sql sql-server-2012

我希望我能够清楚地描绘出我想要实现的目标:

SELECT [Date]
    ,[ChargeCode]
    ,[ChargeDescription]
    ,[HHY_Qty]
    ,[PatPrice]
    , IF ISNUMERIC(HHY_Qty) AND ISNUMERIC(PatPrice)
        BEGIN   
            CAST(HHY_Qty AS INT) * CAST(PatPrice AS INT) AS ExtAmt
        END
        ELSE
            0 AS ExtAmt
        END
FROM [dbo].[ChargeDetails]
WHERE PatientNumber = '1271'

HHY_QtyPatPrice都是MSSQL数据库中的VARCHAR类型。它们是使用来自AS400导出的非常非常脏的CSV的BULK INSERT创建的。在这里,我试图做一些乘法如果字段是数值,否则ExtAmt应该是0.这可能吗?如果没有,是否有解决方法?

1 个答案:

答案 0 :(得分:2)

使用CASE声明:

CASE WHEN ISNUMERIC(HHY_Qty) = 1 AND ISNUMERIC(PatPrice) = 1 THEN CAST(HHY_Qty AS INT) * CAST(PatPrice AS INT) ELSE 0 END AS ExtAmt