UNION ALL、TEXT 字段和 ORDER BY 错误

Posted

技术标签:

【中文标题】UNION ALL、TEXT 字段和 ORDER BY 错误【英文标题】:UNION ALL, TEXT field and ORDER BY error 【发布时间】:2010-10-05 10:05:46 【问题描述】:

我有两个表,其属性类似于date(datetime),headline(varchar),text(text)

现在我想联合所有这两个表并按日期时间排序。执行此操作时出现错误:

工作表中只允许使用文本指针,不允许使用 text、ntext 或 image 列。查询处理器生成的查询计划需要工作表中的 text、ntext 或 image 列。

来回尝试后,我发现是导致错误的文本属性。但是该怎么办?我尝试转换为 VARCHAR 没有成功。两个表都在 text 属性中使用文本格式。

此外,当删除 ORDER BY 时,一切正常。怎么办?

下面是原始的SQL查询,但你可以回复上面的简化。

SELECT     id, datetime, author, headline, intro, text, type, toppriority,
           secondpriority, comments, companyid, '1' source 
FROM     Table1
UNION ALL
SELECT     AutoID AS id, Dato AS datetime,
           ID COLLATE SQL_Latin1_General_CP1_CI_AS AS author, NULL AS headline, 
           NULL AS intro, Notat COLLATE SQL_Latin1_General_CP1_CI_AS AS text,
           CAST(NotatTypeID AS VARCHAR) AS type,
           NULL AS toppriority, NULL AS secondpriority, NULL AS comments,
           Selskabsnummer AS companyid, '2' source 
FROM     Table2
WHERE     (NotatTypeID = '5') OR (NotatTypeID = '6')
ORDER BY datetime DESC

提前致谢

【问题讨论】:

什么版本的SQL,平台等 我认为该错误是特定于 SQL Server 2000 【参考方案1】:

解决此问题的一种方法是将联合作为 sup 查询运行,然后对结果进行排序:

SELECT * FROM 
(
    SELECT     id, datetime, author, headline, intro, text, TYPE, toppriority,
            secondpriority, comments, companyid, '1' source 
    FROM     Table1
    UNION ALL
    SELECT     AutoID AS id, Dato AS datetime,
            ID COLLATE SQL_Latin1_General_CP1_CI_AS AS author, NULL AS headline, 
            NULL AS intro, Notat COLLATE SQL_Latin1_General_CP1_CI_AS AS text,
            CAST(NotatTypeID AS VARCHAR) AS TYPE,
            NULL AS toppriority, NULL AS secondpriority, NULL AS comments,
            Selskabsnummer AS companyid, '2' source 
    FROM     Table2
    WHERE     (NotatTypeID = '5') OR (NotatTypeID = '6')
) a
ORDER BY datetime DESC

【讨论】:

【参考方案2】:

如何将日期时间字段转换为索引中的某个文本字段?请注意,使用 'datetime' 和 'text' 作为字段/别名可能会非常混乱,并且是潜在问题的根源。

【讨论】:

以上是关于UNION ALL、TEXT 字段和 ORDER BY 错误的主要内容,如果未能解决你的问题,请参考以下文章

mysql数据库多个表union all查询并排序的结果为啥错误

union all是啥意思

UNION ALL、UNION与ORDER BY

order by 和union all 如何共存

delphi程序中使用union all 查询sql数据中的两个表报"不能比较或排序 text、ntext和image类型"的错误。

在 MySQL 中使用 Union All 和 Order By