2014-10-01 47 views
0

我有一个看起来像这样的SQL Server数据库:获得新的唯一编号

表结构:

enter image description here

的样本数据:

enter image description here

我想要从表中获得下一个唯一代码

应该来下答案是去年代码为和下面的代码应该是但4已经加入1如此反复存在答案应该是。这个怎么做?任何人都可以帮我一段代码?

回答

1

您可以使用自连接来完成此操作,如下所示。

此SQL正在获取没有后继的第一行代码,并向其添加一个代码。

from子句中的子查询加入0假代码,的情况下的下一个可用的代码是1(如果有一个在@table没有(1, 1),例如)。

declare @table table (id int, code int) 
insert @table values (1, 1), (2, 2), (3, 3), (4, 45), (5, 5) 

select top 1 t1.code + 1 
from (select null as id, 0 as code union all select * from @table) t1 
left join @table t2 on t2.code = t1.code + 1 
where t2.code is null 
order by t1.code 
+0

这就是我一直在寻找的东西,谢谢 – 2014-10-01 03:52:47