求插入算法问题?

particular 2003-11-07 01:41:34
表中有一个字段格式如下:
field
001
002
005
006
007
010
现在想往其中插入数据占003的位置,之后在插入数据占004的位置,在之后为008,009,不知如何写,另处如果有100条数据前98条顺序号都是接着的,插入第099行,如果顺次计算,算法会不会很笨。
...全文
45 9 打赏 收藏 转发到动态 举报
写回复
用AI写文章
9 条回复
切换为时间正序
请发表友善的回复…
发表回复
wzh1215 2003-11-07
  • 打赏
  • 举报
回复
select right(('000'+cast((min(field)+1) as varchar)),3) from #t a where not exists(select 1 from #t where cast(field as int)=cast(a.field as int)+1)
这是表的自链接,right(('000'+cast((min(field)+1) as varchar)),3)是转换数值型为字符型。
cast(field as int)=cast(a.field as int)+1)表内field是否有连续的下一个数据!
particular 2003-11-07
  • 打赏
  • 举报
回复
select right(('000'+cast((min(field)+1) as varchar)),3) from #t a where not exists(select 1 from #t where cast(field as int)=cast(a.field as int)+1)

这句没看明白能解释一下吗?
gmlxf 2003-11-07
  • 打赏
  • 举报
回复
field uname
---------- ----------
001 a
002 b
005 c
006 d
007 e
010 f

(所影响的行数为 6 行)


(所影响的行数为 1 行)

field uname
---------- ----------
001 a
002 b
003 gg --新增加的行
005 c
006 d
007 e
010 f

(所影响的行数为 7 行)
gmlxf 2003-11-07
  • 打赏
  • 举报
回复
--test:
create table #t(field varchar(10),uname varchar(10))
insert #t
select '001','a'
union all select '002','b'
union all select '005','c'
union all select '006','d'
union all select '007','e'
union all select '010','f'
select * from #t

--select right(('000'+cast((min(field)+1) as varchar)),3) from #t a where not exists(select 1 from #t where cast(field as int)=cast(a.field as int)+1)
insert #t
select (select right(('000'+cast((min(field)+1) as varchar)),3) from #t a where not exists(select 1 from #t where cast(field as int)=cast(a.field as int)+1)),'gg'

select * from #t order by field

drop table #t

orcale 2003-11-07
  • 打赏
  • 举报
回复
楼主理解错误了吧
select field from table order by field asc
不就可以了
gmlxf 2003-11-07
  • 打赏
  • 举报
回复
drop table #t
create table #t(field varchar(10),uname varchar(10))
insert #t
select '001','a'
union all select '002','b'
union all select '005','c'
union all select '006','d'
union all select '007','e'
union all select '010','f'
select * from #t

--select right(('000'+cast((min(field)+1) as varchar)),3) from #t a where not exists(select 1 from #t where cast(field as int)=cast(a.field as int)+1)
insert #t
select (select right(('000'+cast((min(field)+1) as varchar)),3) from #t a where not exists(select 1 from #t where cast(field as int)=cast(a.field as int)+1)),'gg'

select * from #t order by field
zqfleaf 2003-11-07
  • 打赏
  • 举报
回复
select top 1 a.number from
(select IDENTITY(INT,1,1) as Number , field from table1 order by field) a
where a.number <> cast(a.field as integer)
order by a.number

gmlxf 2003-11-07
  • 打赏
  • 举报
回复
取出第一缺位:
select min(field)+1 from t a where exists(select 1 from t where field<>field+1)
victorycyz 2003-11-07
  • 打赏
  • 举报
回复
为什么会有这种需求,你清空数据或建新表,然后插入1到100的值不就行了。

34,874

社区成员

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

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