--处理性别随机
select (case when round(rand()*10,0)>5 then '男' else '女' end),
--处理时间段范围内随机
select dateadd(dd,round(datediff(dd,'1992-01-01','1995-01-01')*rand(),0),'1992-01-01')
--添加外键
ALTER TABLE [dbo].[StudnetInfo] WITH CHECK ADD CONSTRAINT [FK_StudnetInfo_StudentClass] FOREIGN KEY([classId])
REFERENCES [dbo].[StudentClass] ([ClassID])
--删除外键
alter table StudnetInfo drop constraint [FK_StudnetInfo_StudentClass]
truncate table StudnetInfo
--查询所有关联约束
exec sp_helpconstraint StudnetInf
--游标处理根据其他表限制的复杂插入
declare @i int, @j int --@i是 @classsum 遍历的记录数,控制while循环;@j记录全部循环的序号
set @j=0
declare cur_temp cursor for select ClassID,ClassSum from StudentClass
open cur_temp
declare @classid varchar(5)
declare @classsum int
fetch next from cur_temp into @classid,@classsum
WHILE @@FETCH_STATUS =0
BEGIN
--print @classid --班级+年份+3位的排序号 0012015001 9位
set @i=0
print @classsum
while(@i<@classsum)
begin
insert into StudnetInfo (StuId,StuName,classId,sex,rx_time,bron)
--处理3位的排序号
select @classid+'2015'+right('00'+convert(varchar(3),@j),3) as 学号,
'邹敏'+convert(varchar(5),@j) as 姓名,
@classid as 班级编号,
(case when round(rand()*10,0)>5 then '男' else '女' end) as 性别,
convert(datetime,left(year(GETDATE()),4)+'-09-01') as 入学时间,
dateadd(dd,round(datediff(dd,'1992-01-01','1995-01-01')*rand(),0),'1992-01-01') as 出生时间
--from StudentClass
set @i=@i+1
set @j=@j+1
end
fetch next from cur_temp into @classid,@classsum
end
close cur_temp
deallocate cur_temp
print @i
print @j
--left(rand())处理取整
--round(rand(),0)四舍五入取值