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

一个插入循环语句的问题?
要实现向一个表里面插入很多条记录,我写了这样一个循环,可是怎么插入的老是一同一条记录呢,
declare   @a   int,
                @classname   varchar(50),
                @classmemo   varchar(50),
                @i   int
set   @a=1
set   @i=1
set   @classname= 'clname '+cast(@i   as   varchar(20))
set   @classmemo= 'clmemo '+cast(@i   as   varchar(20))
while   @a <=100
    begin
      insert   tclass(classname,classmemo)values(@classname,@classmemo)
      set   @a=@a+1
      set   @i=@i+1
    end
go
表结构:
CREATE   TABLE   [dbo].[tClass]   (
[ClassID]   [int]   IDENTITY   (1,   1)   NOT   NULL   ,
[ClassName]   [varchar]   (50)   COLLATE   Chinese_PRC_CI_AS   NOT   NULL   ,
[ClassMemo]   [varchar]   (50)   COLLATE   Chinese_PRC_CI_AS   NULL  
)   ON   [PRIMARY]
GO

------解决方案--------------------
--生成临时表
select top 100 identity(int,1,1) as ID
into #t
from syscolumns a inner join syscolumns b on 1=1

--追加100条记录
insert into tClass (ClassName,ClassMemo)
select 'clname ' + cast(id as varchar(100)), 'clmemo ' + cast(id as varchar(100))
from #t

select * from #t

drop table #t

------解决方案--------------------
declare @a int,
@classname varchar(50),
@classmemo varchar(50),
@i int
set @a=1
set @i=1
while @a <=100
begin

--把这两句放到While中
set @classname= 'clname '+cast(@i as varchar(20))
set @classmemo= 'clmemo '+cast(@i as varchar(20))

insert tclass(classname,classmemo)values(@classname,@classmemo)
set @a=@a+1
set @i=@i+1
end
go