插入排序的问题

leneq 2003-08-19 05:21:06
一般在select * ,identity(int,1,1) as xh from 表 order by 需要排序的字段
这样生成的序号没有没有问题
可当联合表的时候
select *,identity(int,1,1) as xh from 表1 join 表2 on(条件) order by 需要排序的字段
这样生成的序号根本就没有按照order by的字段来排序
在微软的新闻组上问了这样的问题
有人回答这样解决
select *,identity(int,1,1) as xh from (select 字段 from 表1 join 表2)
as 表名 order by 需要排序的字段
我试了一下,也不行
在这里提出来,大家讨论一下好不好?
...全文
98 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
leneq 2003-08-20
  • 打赏
  • 举报
回复
re
我创建了一个临时表#Report,要把#Report的数据排序后插入#ReportSC
语句是:select a,code,b,c,d,e
into #ReportSC
from #Report t1 inner join t2 on t1.a=t2.a
order by t2.code,cast(b as int),cast(c as int),d
然后修改#ReportSC每一行的e数据
然后输出,结果排序结果非常奇怪,看上去是按code排序了,结果是把后面许多行的数据插入中间了,这是怎么回事呢

你这个情况跟我的差不多,在联合表查询时,这种情况就出现了
jntvip 2003-08-19
  • 打赏
  • 举报
回复
我创建了一个临时表#Report,要把#Report的数据排序后插入#ReportSC
语句是:select a,code,b,c,d,e
into #ReportSC
from #Report t1 inner join t2 on t1.a=t2.a
order by t2.code,cast(b as int),cast(c as int),d
然后修改#ReportSC每一行的e数据
然后输出,结果排序结果非常奇怪,看上去是按code排序了,结果是把后面许多行的数据插入中间了,这是怎么回事呢
pengdali 2003-08-19
  • 打赏
  • 举报
回复
我想尽量的介绍临时表的数量
select *,identity(int,1,1) as xh into #temp from 表1 join 表2 on(条件) order by 需要排序的字段

re:
你无论如何都要一个临时表。你写的和:
select * into #temp from 表1 join 表2 on(条件) order by 需要排序的字段
ALTER TABLE #temp ADD xh int identity(1,1) not null
不是一样效果吗?

其实加一个中间表很容易解决问题,问题的关键是sql server在联合表时不识别的这样的ordrer by,不联合时是没有问题的,

sqlserver在先排序先into是不确定的。你做一个复杂的查询的时候就会有这个问题,你这个问题,我也碰到过,我还和别人争论,应为当时只有我的sqlserver(正版)会出现这个问题。同样的语句结果和别人就是不同。我用4台sqlserver得出的结构正好2、2开,2个是对的2个和你一样。4台的区别就是没打补丁。
leneq 2003-08-19
  • 打赏
  • 举报
回复
我想尽量的介绍临时表的数量
select *,identity(int,1,1) as xh into #temp from 表1 join 表2 on(条件) order by 需要排序的字段
其实加一个中间表很容易解决问题,问题的关键是sql server在联合表时不识别的这样的ordrer by,不联合时是没有问题的,
我想不光是打sp3这么简单,可能是内置的一些属性或者一些应该避免的地方我们没有注意到??
ysycrazy 2003-08-19
  • 打赏
  • 举报
回复
同意 pengdali(大力 V2.0)
pengdali 2003-08-19
  • 打赏
  • 举报
回复
这个问题,原来讨论过你打个sp看看。sp3

http://www.microsoft.com/china/sql/downloads/sp3.asp

不过我写的,是100%可以的。反正你要into出一个临时表的。
leneq 2003-08-19
  • 打赏
  • 举报
回复
回 CrazyFor(太阳下山明朝依旧爬上来)
你是用了一个中间表,如果不用这样办法呢?sql为什么在联合表的时候就不按照order by后面的规则了呢?
leneq 2003-08-19
  • 打赏
  • 举报
回复
o,对了,写错了,是需要写into 表的,我忘记写了
CrazyFor 2003-08-19
  • 打赏
  • 举报
回复
TRY:

select * into #temp from (select 字段 from 表1 join 表2)
as 表名 order by 需要排序的字段

select *,identity(int,1,1) as xh into #tempB from #temp
zjcxc 2003-08-19
  • 打赏
  • 举报
回复
不会吧?

你不生成表,只查询,会排序吗?
pengdali 2003-08-19
  • 打赏
  • 举报
回复
select * into #临时表 from 表1 join 表2 on(条件) order by 需要排序的字段

ALTER TABLE #临时表 ADD xh int identity(1,1) not null

100%可以。

22,207

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server 疑难问题
社区管理员
  • 疑难问题社区
  • 尘觉
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧