使用UNION ALL时“转换失败...”,但单独运行查询有效

时间:2015-12-15 01:04:40

标签: sql-server trim union-all

我正在尝试使用SELECT INTOUNION ALL将3个表连接在一起。

表1使用了许多Ltrim(Rtrim())CONVERT命令,而对于其他两个表,我只是将它们的列移出并粘贴到这个组合表中。

当我尝试运行查询时,收到一条错误消息:

  

从字符转换日期和/或时间时转换失败   字符串。

但是单独处理表格,一切都顺利进行。

这是什么原因,我该如何解决?

编辑:这是前两个表的并集示例;

SELECT
    , CONVERT(DATE, [GL DATE], 101) AS [Date1]
    , CONVERT(FLOAT, [Amount_01]) AS [Amt]
INTO #big_table
FROM table1    
UNION ALL

    [POSDATE] AS [Date1]
    , [NET] AS [Amt] NULL AS [Date_Up]
    , NULL AS [Time_up]
    ,
FROM table2

编辑#2:

我找到了故障列,它们是 [Date1]和[Amt]。

对于表1,以下是来自这两列的样本数据:

 Date1            Amt   
4/28/2014        216.43
4/28/2014        1526.61
4/28/2014        13.61
4/27/2014        177.9
4/27/2014        489.58

表2:

  Date1         Amt
30/04/2014       -7501.9
30/04/2014       0
30/03/2014       -75201.9
30/03/2014       0
28/02/2014       -25247.93
28/02/2014       0

表3:

   Date1           Amt
21/04/2014      100,000,000.00
21/04/2014      -2,312,314.44
21/04/2014      -100,000,000.00
21/04/2014      56.41
26/04/2014      2,312,314.44
26/04/2014      -125.4

如果我没有弄错,表2和表3中Date1的格式与表1相比有问题,因为2和3是:DD/MM/YYYY,而表1是{ {1}}。

但为什么MM/DD/YYYY不起作用?可以将非正数转换为浮点数吗?

我如何解决此问题并进行有效转换?

编辑3 :对于表3:

我尝试过使用 CONVERT(DATE,[Date1],103)它有效, 但是,尽管具有相同的输入/输出结构,表2中的相同策略也失败了 - 这可能是什么原因?

我再次收到:

  

从字符串转换日期和/或时间时转换失败。

1 个答案:

答案 0 :(得分:2)

SELECT INTO will create a table, and in doing so it will make assumptions about what data types to use when creating the table if you have applied conversions to some of the columns. It should be pretty simple to look at the two existing tables and note the date/time/string fields, and make sure that the UNION columns that match these columns are typed correctly.

So, for instance, if column 1 in your other two tables are both strings, and column 1 in your SELECT INTO table is a date/time, you can use SELECT convert(varchar,Col1) AS yourColName, so that it will merge with the string type in the other two tables.

It would help if you posted your query code and table definitions.