如何一条语句生成多条记录

moudy 2017-03-21 11:05:29
假设我有一个表
CREATE TABLE #temp(id BIGINT IDENTITY(1,1), other VARCHAR(20) NULL)

如何用一条语句在该表插入100条记录

不能用循环,也不能从别的表select top 100

请教各位高手!
...全文
142 11 打赏 收藏 转发到动态 举报
写回复
用AI写文章
11 条回复
切换为时间正序
请发表友善的回复…
发表回复
唐诗三百首 2017-03-21
  • 打赏
  • 举报
回复

insert into #temp(other)
 select 'num'+rtrim(number)
  from master.dbo.spt_values
  where type='P' 
  and number between 1 and 100
二月十六 版主 2017-03-21
  • 打赏
  • 举报
回复
还不能从别的表select top 100.。。。
moudy 2017-03-21
  • 打赏
  • 举报
回复
引用 10 楼 ap0405140 的回复:
弱弱的问一下, LZ的这个需求应该不算复杂吧. 为何要人为加上诸多限制? "不能用循环,也不能从别的表select top 100, 不用借用其他表"... 建议: 目标明确的情况下, 不管用什么方法(越简单越好), 能实现,达到需求的目的就好, 没必要人为制造诸多限制,意义何在.
只是探讨一下,因为用那几种方法我都会。 程序员的通病,技术上喜欢钻牛角尖。
唐诗三百首 2017-03-21
  • 打赏
  • 举报
回复
弱弱的问一下, LZ的这个需求应该不算复杂吧. 为何要人为加上诸多限制? "不能用循环,也不能从别的表select top 100, 不用借用其他表"... 建议: 目标明确的情况下, 不管用什么方法(越简单越好), 能实现,达到需求的目的就好, 没必要人为制造诸多限制,意义何在.
moudy 2017-03-21
  • 打赏
  • 举报
回复
引用 8 楼 ap0405140 的回复:

declare @times int,@i int
declare @sql nvarchar(1000)

select @times=100,
       @i=1,
       @sql=N'insert into #temp(other) values(''XX''); '

while(@i<=@times)
begin
 exec(@sql)
 set @i=@i+1
end
能不用循环实现吗?
唐诗三百首 2017-03-21
  • 打赏
  • 举报
回复

declare @times int,@i int
declare @sql nvarchar(1000)

select @times=100,
       @i=1,
       @sql=N'insert into #temp(other) values(''XX''); '

while(@i<=@times)
begin
 exec(@sql)
 set @i=@i+1
end
moudy 2017-03-21
  • 打赏
  • 举报
回复
引用 4 楼 wmxcn2000 的回复:
insert into #temp(other) values('XX') go 100
大神,数量如果是动态的,如何用该方法实现? CREATE TABLE #temp(id BIGINT IDENTITY(1,1), other VARCHAR(20) NULL) DECLARE @times INT SET @times = 100 DECLARE @sql NVARCHAR(1000) SET @sql = 'insert into #temp(other) values(''XX'') '+CHAR(13)+ CHAR(10)+'GO ' +CONVERT(NVARCHAR(10),@times) EXEC sp_executesql @sql DROP TABLE #temp 运行会报错,如下: Msg 102, Level 15, State 1, Line 2 Incorrect syntax near 'GO'. 如何解决?
㤁孞 2017-03-21
  • 打赏
  • 举报
回复
膜拜楼上的大神们
moudy 2017-03-21
  • 打赏
  • 举报
回复
引用 4 楼 wmxcn2000 的回复:
insert into #temp(other) values('XX') go 100
果然牛人。。。
卖水果的net 版主 2017-03-21
  • 打赏
  • 举报
回复
insert into #temp(other) values('XX') go 100
moudy 2017-03-21
  • 打赏
  • 举报
回复
引用 2 楼 ap0405140 的回复:

insert into #temp(other)
 select 'num'+rtrim(number)
  from master.dbo.spt_values
  where type='P' 
  and number between 1 and 100
不错~ 还有没有其他方法,不用借用其他表。

34,587

社区成员

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

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