我现在有两个表
如TABLE1 字段名 SN1 类型为INT
TABLE2 字段名 SN2 类型为 INT
TABLE3 字段名 SN3 类型为 INT
有一个模块:模块一在不断的往TABLE1(SN1)和TABLE2(SN2)里 写入不连续的正整数。
而模块二也要往TABLE3里面SN3插入整数,每次插入的数字是所有TABLE1和TABLE2中的SN1和SN2组成的递增数字中的最小缺少值。如
TABLE1中SN1 1、3
TABLE2中SN2 5、7
那么模块二第一次插入的必须是 2,之后可以是4等,且TABLE1和TABLE2里面的数字都在不断增多的
我想了个算法很复杂,就是先取出来,再排序,然后在循环查找,
那位能否帮我想下简单的思路,我在DELPHI下开发,可以配合环境特色去做算法。谢谢~!
如TABLE1 字段名 SN1 类型为INT
TABLE2 字段名 SN2 类型为 INT
TABLE3 字段名 SN3 类型为 INT
有一个模块:模块一在不断的往TABLE1(SN1)和TABLE2(SN2)里 写入不连续的正整数。
而模块二也要往TABLE3里面SN3插入整数,每次插入的数字是所有TABLE1和TABLE2中的SN1和SN2组成的递增数字中的最小缺少值。如
TABLE1中SN1 1、3
TABLE2中SN2 5、7
那么模块二第一次插入的必须是 2,之后可以是4等,且TABLE1和TABLE2里面的数字都在不断增多的
我想了个算法很复杂,就是先取出来,再排序,然后在循环查找,
那位能否帮我想下简单的思路,我在DELPHI下开发,可以配合环境特色去做算法。谢谢~!
解决方案 »
- sql语句优化,select top 1 表1 where 某字段='*' order by 更新时间 DESC
- 『木鱼』 SQL500 之代码:怎样才能使SQL代码既规范又美观
- 求验证,数据库作业ID的问题
- 删除重复记录的特殊情况
- 求一条查询语句(不是特别难)
- 求解存储过程xp_dirtree是如何实现的
- Sql sever数据库表的字段里存放压缩的CAD图纸
- 当时间过期时执行语句
- 只查询允许有8行,不够就补为空行,这样的SQL语句怎么写呀?
- SQLSERVER2008可以远程访问但本机无法访问
- 字符串查询,请教一下
- 查询语句中既要用到 left outer join,又要用到where,应该怎么写?谁在前面谁在后面?
FROM TABLE3 AS a ,TABLE3 AS b where a.SN3 >= b.SN3
GROUP BY a.SN3)
WHERE (ab <> SN3)
ORDER BY ab
declare @table1 table
(SN1 int)
declare @table2 table
(SN2 int)
declare @table3 table
(SN3 int)
declare @maxvalue intinsert into @table1
select 1
union
select 2
insert into @table2
select 4
union
select 5select identity(int,1,1)as idx ,*
into #table
from
(
select SN1
from @table1
union
select SN2
from @table2
union
select SN3
from @table3)aset @maxvalue=(select max(SN1)from #table)+1insert into @table3
(SN3)
select isnull(min(idx),@maxvalue) from #table where idx<>SN1select * from @table3
drop table #table
set nocount off
修正方案为将identity(int,1,1)中间的1用变量替代,并将全句改写成字符串测试语句如下set nocount on
create table #table1
(SN1 int)
create table #table2
(SN2 int)
create table #table3
(SN3 int)
declare @maxvalue int
declare @minvalue int
insert into #table3 values(4)
insert into #table1
select 2
union
select 3
insert into #table2
select 5
union
select 6
set @minvalue=(select min(SN1)
from
(
select SN1
from #table1
union
select SN2
from #table2
union
select SN3
from #table3
)a)exec('select identity(int,'+@minvalue+',1)as idx ,*
into #table
from
(
select SN1
from #table1
union
select SN2
from #table2
union
select SN3
from #table3
)a
declare @maxvalue int
set @maxvalue=(select max(SN1)from #table)+1insert into #table3
(SN3)
select isnull(min(idx),@maxvalue) from #table where idx<>SN1select * from #table3
drop table #table
drop table #table1
drop table #table2
drop table #table3
')set nocount off
下列SQL代码实现你的要求SELECT (CASE WHEN EXISTS(SELECT * FROM TMP b WHERE b.tid = 1) THEN MIN(tid) + 1 ELSE 1 END) as tid FROM tmp WHERE NOT tid IN (SELECT a.tid - 1 FROM tmp a)