日期:2014-05-19  浏览次数:20670 次

怎么同时插入多条相同的记录,但流水号自动累加?
假如有张表有id、a、b三个字段,我要把“2007071500060”“学生”和“教师”分别插入到id、a、b字段里10次       或更多?但id里要自动累加,效果:
      id                           a               b
2007071500060       学生           教师  
2007071500061       学生           教师  
2007071500062       学生           教师  
......

------解决方案--------------------
用个循环,用个变量,搞定
declare @n int
set @n = 1
while(@n <10)
begin
insert 表
(select convert (char(4),datepart(year,getdate()))+ convert (varchar(2),datepart(month,getdate()))+ convert (varchar(2),datepart(day,getdate()))+
convert(char(5),@n), '学生 ', '教师 ')
set @n = @n+1
end
------解决方案--------------------
可以寫一個循環

declare @t table(
id varchar(13),
a varchar(10),
b varchar(10))


declare @i int, @id varchar(13)
select @i = 1, @id = '2007071500060 '
while @i <= 10 --這裏的10可以改為你需要的次數
begin
insert @t select @id, '学生 ', '教师 '
set @id = left(@id, 8) + right( '00000 ' + ltrim(cast(right(@id, 5) as int) + 1), 5)
set @i = @i + 1
end

--結果
select * from @t

/*
id a b
------------- ---------- ----------
2007071500060 学生 教师
2007071500061 学生 教师
2007071500062 学生 教师
2007071500063 学生 教师
2007071500064 学生 教师
2007071500065 学生 教师
2007071500066 学生 教师
2007071500067 学生 教师
2007071500068 学生 教师
2007071500069 学生 教师

(所影响的行数为 10 行)
*/