SQL查询中的数据类型转换

时间:2015-12-17 13:24:45

标签: sql sql-server

我有以下查询,其中我尝试添加两个数据类型为nvarchar的列。它只给我连接。请查看下面的查询:

SELECT 
    T0.[ItmsGrpCod],
    T1.[Dscription],
    T3.[OnHand] as 'Opening balance',
    (T1.[U_TotalGraded]) + (T1.[U_TotalRej]),
    T1.[U_TotalGraded], T1.[U_TotalRej], 
    T2.[DocDate] 
FROM 
    OITM T0
INNER JOIN 
    IGN1 T1 ON T0.[ItemCode] = T1.[ItemCode] 
INNER JOIN 
    OIGN T2 ON T1.[DocEntry] = T2.[DocEntry] 
INNER JOIN 
    OITW T3 ON T0.[ItemCode] = T3.[ItemCode]

现在,如果T1.[U_TotalGraded] = 12T1.[U_TotalRej] = 3,我将收到(T1.[U_TotalGraded])+(T1.[U_TotalRej]) = 123而不是添加。

1 个答案:

答案 0 :(得分:3)

您可以使用以下代码中的INT将其转换为CAST

   SELECT 
       T0.[ItmsGrpCod], 
       T1.[Dscription], 
       T3.[OnHand] as 'Opening balance',
       case when isnumeric(T1.[U_TotalGraded]) = 1 and 
                 isnumeric(T1.[U_TotalRej]) = 1 
            then cast(T1.[U_TotalGraded] as int) + cast(T1.[U_TotalRej] as int) 
            else 0 -- do something if can't be converted
       end,
       T1.[U_TotalGraded], 
       T1.[U_TotalRej], 
       T2.[DocDate] 
   FROM OITM T0  
   INNER JOIN IGN1 T1 ON T0.[ItemCode] = T1.[ItemCode] 
   INNER JOIN OIGN T2 ON T1.[DocEntry] = T2.[DocEntry] 
   INNER JOIN OITW T3 ON T0.[ItemCode] = T3.[ItemCode]

此外,您可以使用ISNUMERIC检查是否可以将其转换为数据类型INT