怎么查询中产生固定格式的序号,在线结贴...

gopark 2006-06-27 10:31:32
我要把一个表的数据导入另一个表,但要加个序号列,格式如"M06060001",有办法吗?
...全文
274 10 打赏 收藏 转发到动态 举报
写回复
用AI写文章
10 条回复
切换为时间正序
请发表友善的回复…
发表回复
冷箫轻笛 2006-06-27
  • 打赏
  • 举报
回复
to:paoluo(一天到晚游泳的鱼)

说的好!!!

:)
paoluo 2006-06-27
  • 打赏
  • 举报
回复
用一條語句的前提是,表中有一個不重復的字段,而且生成單號的規律完全符合該字段的排序。
冷箫轻笛 2006-06-27
  • 打赏
  • 举报
回复
:)
借用一下paoluo(一天到晚游泳的鱼) 的数据:

--一条语句
insert into b
select 'M'+ Convert(Varchar(4),GetDate(),12)+Right(10000+ID,4),Name
from
(select id = (select count(1) from a where name <= t1.name),name
from a t1
)t2

--结果:select * from b
M06060005 liu
M06060001 bb
M06060002 cc
M06060003 dd
M06060004 ee
liangpei2008 2006-06-27
  • 打赏
  • 举报
回复
paoluo(一天到晚游泳的鱼) 大哥厉害!我没有挖掘到这些信息:(
fcuandy 2006-06-27
  • 打赏
  • 举报
回复
我的理解跟鱼的一样。

如果楼主表中有标识列,还可以不用临时表。
paoluo 2006-06-27
  • 打赏
  • 举报
回复
中間的0606應該是當前日期的年月吧。
paoluo 2006-06-27
  • 打赏
  • 举报
回复
Create Table A(Name Varchar(50))
Insert A Select 'liu'
Union All Select 'bb'
Union All Select 'cc'
Union All Select 'dd'
Union All Select 'ee'

Create Table B(ID Char(9),Name Varchar(50))
GO
Select ID=Identity(Int,1,1),* Into #T From A
Insert B Select 'M'+ Convert(Varchar(4),GetDate(),12)+Right(10000+ID,4),Name From #T

Select * From B
Drop Table #T
GO
Drop Table A,B
--Result
/*
ID Name
M06060001 liu
M06060002 bb
M06060003 cc
M06060004 dd
M06060005 ee
*/
liangpei2008 2006-06-27
  • 打赏
  • 举报
回复
楼上厉害:)
select *,identity(int,1,1) as id into # from 表名--加序号
------------------
insert 表名(id,..)
select 'M'+right(106060000+id,8)
from #
冷箫轻笛 2006-06-27
  • 打赏
  • 举报
回复
--别忘了
drop table #tab

:)
冷箫轻笛 2006-06-27
  • 打赏
  • 举报
回复
select identity(int,1,1) as id , * into #tab from 原表

insert into 目标表(id,...)
select 'M0606'+ right('0000'+ cast(id as varchar),4),...
from #tab

====================================

一条数据也可以,不过语句稍微麻烦一点!

34,590

社区成员

发帖
与我相关
我的任务
社区描述
MS-SQL Server相关内容讨论专区
社区管理员
  • 基础类社区
  • 二月十六
  • 卖水果的net
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

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