日期:2014-05-18  浏览次数:20596 次

自动生成流水号的问题
流水号有这些元素:楼,房间,架子,行,列
假设现在有20栋楼,每栋楼有30个房间,每个房间有15个架子,每个架子有10行,20列
怎么样写个循环来自动自动生成上面的流水号从第一个:0101010101到最后一个2030151020

------解决方案--------------------
SQL code
if object_id('tempdb.dbo.#') is not null drop table #

create table #
(
    i int identity(0,1),
    id as right('0'+ltrim(i/90000+1),2)+right('0'+ltrim(i/3000%30+1),2)+right('0'+ltrim(i/200%15+1),2)+right('0'+ltrim(i/20%10+1),2)+right('0'+ltrim(i%20+1),2),
    data varchar(1)
)

insert # select 'a'
insert # select 'b'

select * from #

/*
i           id                   data
----------- -------------------- ----
0           0101010101           a
1           0101010102           b
*/

------解决方案--------------------
SQL code
declare
   @i int -- loop
declare @n table (n int)
set @i=1
while @i<100 begin
  insert into @n values (@i)
  set @i=@i+1
end

select 
    right(cast(100+t as varchar),2) -- 楼
  + right(cast(100+r as varchar),2) -- 房间
  + right(cast(100+b as varchar),2) -- 架子
  + right(cast(100+x as varchar),2) -- 行
  + right(cast(100+y as varchar),2) -- 列
from
  (select t=n from @n where n <= 20) as t, -- 20栋楼
  (select r=n from @n where n <= 30) as r, -- 30个房间
  (select b=n from @n where n <= 15) as b, -- 15个架子
  (select x=n from @n where n <= 10) as x, -- 10行
  (select y=n from @n where n <= 20) as y -- 20列