SQLServer 有这样一种情况 能不能用一个SQL文实现

来源:百度知道 编辑:UC知道 时间:2024/06/23 19:16:06
一个表
ID 是6位的 TYPE 是1位的
存放ID 0000-9999 TYPE 0 和
存放ID 000000-999999 TYPE 1 的数据

现在表里面有下面这样的数据
0000 0
0001 0
0004 0
0005 0
000001 1
000004 1
000006 1

想要取得 0 的时候 0002 这个没有被使用的最小ID
1 的时候 000000 这个没有被使用的最小ID

怎么做啊???
就是程序当0的时候 要得到0002 这个没有被用过的ID
1的时候 要得到000000 这个没有被用过的ID

1个SQL文 就是一个SELECT操作阿

就像这样(当然有问题的)
SELECT MIN(A.ROWNUM) - 1 FROM
(SELECT ROW_NUMBER() OVER (ORDER BY ID) AS ROWNUM FROM [TABLE]) A
LEFT JOIN
(SELECT ID FROM [TABLE]) B
on A.ROWNUM - 1 = B.ID
WHERE A.TYEP = 0 AND B.ID IS NULL

用一个语句实现有点难,用一个存储过程实现是没问题的,一个SQL文是什么意思?
看看吧,哈哈,这的确是一个语句:
---------------------------------------------
select newid=right(convert(varchar,min(newid)+10000),4),type=0 from (select newid=convert(int,id)+1,type from (select * from table1 where type=0 union select id='-0001',type=0) a where id+1>=0 and id+1 not in(select convert(int,id) from table1 where type=0)) a
union
select newid=right(convert(varchar,min(newid)+1000000),6),type=1 from (select newid=convert(int,id)+1,type from (select * from table1 where type=1 union select id='-000001',type=1) a where id+1>=0 and id+1 not in(select convert(int,id) from table1 where type=1)) a
---------------------------------------------
这是边实验边作的,完全通过!!
受了你上面的语句中(减1)的启发,用了加1,能看清吧?

用存储过程,根据TYPE的不同从id=0000或者id=000000判断起,如果该id在数据库中存在则id+1再次判断,直至不在跳出循环