表达式类型数字对于整理是无效的

时间:2015-10-07 11:32:34

标签: sql-server sql-server-2008-r2

我忙于在不同数据库之间使用SQL中的UNION ALL。

SELECT     CostValue AS [COST OF SALES], Customer AS [CUSTOMER CODE], DocumentType AS [DOCUMENT TYPE], Invoice AS [INVOICE NO], InvoiceDate AS [INVOICE DATE], 
                  DATEPART(dd, InvoiceDate) AS [INVOICE DAY], Mass AS MASS, NetSalesValue AS SALES, NetSalesValue - CostValue AS [GROSS PROFIT], OrderType, 
                  QtyInvoiced AS QUANTITY, SalesOrder, StockCode AS [STOCK CODE], TrnMonth AS [FIN MONTH], TrnYear AS [FIN YEAR], TrnYear * 100 + TrnMonth AS YYYYMM, 
                  'SHP' AS COMPANY
FROM         SomeCompanyA.dbo.SalesDetail
WHERE     (LineType = 1) AND (TrnYear >= 2010)
UNION ALL
SELECT     CostValue AS [COST OF SALES], Customer AS [CUSTOMER CODE],     DocumentType AS [DOCUMENT TYPE], Invoice AS [INVOICE NO], InvoiceDate AS [INVOICE DATE], 
                  DATEPART(dd, InvoiceDate) AS [INVOICE DAY], Mass AS MASS, NetSalesValue AS SALES, NetSalesValue - CostValue AS [GROSS PROFIT], OrderType, 
                  QtyInvoiced AS QUANTITY, SalesOrder, StockCode AS [STOCK CODE], TrnMonth AS [FIN MONTH], TrnYear COLLATE DATABASE_DEFAULT AS [FIN YEAR], (TrnYear * 100) COLLATE database_default + TrnMonth AS YYYYMM, 
                  'SGF' AS COMPANY
FROM         SQLXXXXXX.SomeCompanyB.dbo.SalesDetail AS SalesDetail_1
WHERE     (LineType = 1) AND (TrnYear >= 2010)

我在执行时收到以下错误"表达式类型numeric对于COLLATE子句"我认为它来自于此(TrnYear * 100)COLLATE database_default + TrnMonth AS YYYYMM

我不确定如何处理这个,因为我将其理解为连接而不是隐式转换。

请有人提供一些关于如何正确投射的建议。

我也在这里看了Use Collate in CONCAT,但我不知道这会如何起作用,因为我在这一年使用了一个运营商。

也许我错过了什么。任何意见,将不胜感激。

谢谢

1 个答案:

答案 0 :(得分:2)

COLLATE用于文本类型,(TrnYear * 100)计算为数字。在使用COLLATE之前,尝试使用CAST((TrnYear * 100)AS VARCHAR)转换为varchar。