读书人

请教通过union联合两条Select语句后的

发布时间: 2012-02-01 16:58:19 作者: rapoo

请问通过union联合两条Select语句后的排序问题?
请问,如果表A和表B的字段是相同的,
但唯一的是表A的a字段是int型的,而表B的a字段是nvarChar型的;
要联合查询这两个表(select from A union select from B)
而且要通过a字段进行整型排序,该怎么处理?

我用:select a,a1,a2 from A
union
select a,a1,a2 from B
order by a
时,出错:“将 varchar 值转换为数据类型为 int 的列时发生语法错误。”

如果:select a=convert(char,a),a1,a2 from A
union
select a=convert(char,a),a1,a2 from B
order by a
时,是可以,但是按字符排序的。

如果用分开查询却不符合设计要求,现急中。。。

[解决办法]
declare @ta table(a int,a1 nvarchar(10),a2 nvarchar(10))
insert @ta
select 1, 'x ', 'y ' union all
select 2, 'x ', 'y ' union all
select 3, 'x ', 'y '
declare @tb table(a nvarchar(10),a1 nvarchar(10),a2 nvarchar(10))
insert @tb
select '4 ', 'x ', 'y ' union all
select '5 ', 'x ', 'y ' union all
select '6 ', 'x ', 'y '

select a,a1,a2 from @ta
union all
select cast(a as int),a1,a2 from @tb order by a DESC

/*结果
a a1 a2
----------- ---------- ----------
6 x y
5 x y
4 x y
3 x y
2 x y
1 x y
*/

[解决办法]
当 表B 的 a 列包括 'w4 '这样的字符时怎么能安照整型排序呢?
或者你是有别的要求?

读书人网 >SQL Server

热点推荐