日期:2014-05-19  浏览次数:20649 次

如何增加一个序号?
比如我要联合两张表
select   *   tbStu1   UNION   select   *   tbStu2

tbStu1
王二   男   广东

tbStu2
张三   男   山东

现在需要得到下列一张表
1   王二   男   广东
2   张三   男   山东
该如何做呢?谢谢

------解决方案--------------------
select id=identity(int,1,1),t.*
into newtable
from (select * from tbStu1 UNION select * from tbStu2)t
------解决方案--------------------
Select identity(int,1,1) as id,* into 新表
from (select * from tbStu1 UNION
select * from tbStu2) as t
------解决方案--------------------
identity只用于select into 句型中
------解决方案--------------------
楼上说得有道理。
------解决方案--------------------
2005有函数可以直接编号,2000没有这个功能.
如果你有另外一个字段可以唯一排序(比如创建时间),也可以实现.
不然得使用临时表
------解决方案--------------------
没有办法,只能用临时表

select pid=identity(int,1,1),t.* into #table_Pqs
from (select * from tbStu1 union select * from tbStu2) as t

select * from #table_Pqs

drop table #table_Pqs

------解决方案--------------------
2005可以用row_number:
create table ta(id int,name int)
insert ta select 1,2 union all select 1,3


select *,row=ROW_NUMBER () over (order by id)
from ta

--drop table ta


------解决方案--------------------
select 序列=identity(int,1,1),* into #temp from (select * from @tbStu1 UNION all select * from @tbStu2) b
------解决方案--------------------
select 序号=identity(int,1,1),* into # from (select * tbStu1 UNION select * tbStu2) b
然后
select * from #