消息402,级别16,状态1,第4行数据类型varchar和varchar在减法运算符中不兼容

时间:2018-08-09 04:09:09

标签: sql sql-server

我正在编写以下代码

SELECT
    customer_Id,
    DOB,
    DATEDIFF(MONTH, CONVERT(date, Customer.DOB, 103), GETDATE()) AS [Age IN Months],
    Gender,
    city_code,
    Qty,
    (total_amt - (Rate + Tax)) AS [Total_sale_amt]
FROM 
    Customer
JOIN 
    Transactions ON Customer.customer_Id = Transactions.cust_id
ORDER BY 
    [Age IN Months] DESC;

最终出现以下错误消息

  

消息402,第16级,状态1,第4行
  减运算符中的数据类型varchar和varchar不兼容。

请按照本节的内容通知我

( total_amt - ( Rate + Tax ) ) AS [ Total_sale_amt ]

我打算在其他所有列之外增加一个销售数字列。

下面是我的桌子的样子

enter image description here

谢谢!

2 个答案:

答案 0 :(得分:0)

好像( total_amt - ( Rate + Tax ) )列中的一列还是varchar。根据您的要求Cast/Convertint/Float/Decimal的所有列。

对于以下查询,我假设您的totalamt, Rate, Taxvarchar字段。

 SELECT
        customer_Id,
        DOB,
        DATEDIFF( MONTH, CONVERT ( date, Customer.DOB, 103 ),GETDATE ( ) ) AS [ Age IN Months ],
        Gender,
        city_code,
        Qty,

        ( cast(total_amt as FLOAT) - ( cast(Rate as float) + cast(Tax  as float)) ) AS [ Total_sale_amt ]
    FROM Customer
    JOIN Transactions
        ON Customer.customer_Id = Transactions.cust_id
    ORDER BY [ Age IN Months ] DESC;

答案 1 :(得分:0)

您唯一的减法运算符是:

(total_amt - (Rate + Tax)) AS [Total_sale_amt]

这表明其中之一是字符串-不能隐式转换。我建议寻找这些值:

select total_amt, rate, tax
from ?  -- don't know which table these are in
where try_convert(decimal(20, 4), total_amt) is null or
      try_convert(decimal(20, 4), rate) is null or
      try_convert(decimal(20, 4), tax) is null;

这将显示有问题的值。一旦知道需要修复的内容,您将需要修复数据或询问有关如何修复数据的另一个问题。