有关转换SQL查询联合的数据类型的问题

时间:2019-02-05 15:59:40

标签: sql sql-server type-conversion

我写了以下查询以合并生产订单和库存转移的未清项目。对于OWOR表中的查询(全部合并后)

我遇到错误

  

将数据类型nvarchar转换为数字时出错

我尝试将小数(最初是6个字符转换为2个字符)

    Select  t15.ObjType, t15.shipdate, t15.docentry, t15.linenum, 
    t15.linestatus, t15.itemcode, t15.Dscription, t15.Quantity, t15.OpenQty, 
    t15.price, t15.Currency, t15.rate, t15.DiscPrcnt, t15.LineTotal, 
    t15.OpenSum, t15.VendorNum, t15.WhsCode,
    CASE
       WHEN t15.objtype = 67 THEN 'Inventory Transfer Request' 

       ELSE 'unknown'
     END AS Document_Type


    From wtq1 t15

    Union all

    Select t16.ObjType, T16.DueDate, T16.Docentry, T16.ProdName, 
    T16.ItemCode, T16.Uom, CONVERT(DECIMAL(18,2), T16.PlannedQty), 
    CONVERT(DECIMAL(18,2), T16.CmpltQty), T16.Status, T16.PostDate, 
    T16.CloseDate, T16.CreateDate, T16.UpdateDate, T16.Warehouse, 
    T16.JrnlMemo, T16.Priority, T16.Printed,

    CASE 
    WHEN t16.ObjType = 202 THEN 'Production Order'

    ELSE 'Unknown'
    END AS Document_Type

    From owor T16

1 个答案:

答案 0 :(得分:4)

使用UNION时,所有对应的列都必须具有相同的数据类型。
如果没有,那么如果可能的话,可能会有隐式的数据类型转换。
在您的情况下,通过仅读取列的名称,我只能猜测各列之间存在某些不匹配:

t15.ObjType     t16.ObjType 
t15.shipdate    T16.DueDate 
t15.docentry    T16.Docentry 
t15.linenum     T16.ProdName 
t15.linestatus  T16.ItemCode 
t15.itemcode    T16.Uom 
t15.Dscription  CONVERT(DECIMAL(182) T16.PlannedQty) 
t15.Quantity    CONVERT(DECIMAL(182) T16.CmpltQty) 
t15.OpenQty     T16.Status 
t15.price       T16.PostDate 
t15.Currency    T16.CloseDate 
t15.rate        T16.CreateDate 
t15.DiscPrcnt   T16.UpdateDate 
t15.LineTotal   T16.Warehouse 
t15.OpenSum     T16.JrnlMemo 
t15.VendorNum   T16.Priority 
t15.WhsCode     T16.Printed

亲自检查一下,但我认为至少这些对:

t15.OpenQty     T16.Status 
t15.price       T16.PostDate 
t15.Currency    T16.CloseDate 
t15.rate        T16.CreateDate 
t15.DiscPrcnt   T16.UpdateDate 

是无与伦比的,就像其他人一样。