Sql 使用while循环在表中插入多条记录
我想在一个表中插入几百行,该表指向另一个表中的pk。我一直在尝试使用while循环在表中插入多条记录。我实际上是在设置我的测试数据 这就是我正在做的:Sql 使用while循环在表中插入多条记录,sql,sql-server,tsql,Sql,Sql Server,Tsql,我想在一个表中插入几百行,该表指向另一个表中的pk。我一直在尝试使用while循环在表中插入多条记录。我实际上是在设置我的测试数据 这就是我正在做的: declare @count int; set @count = 4018; while @count <= 5040 begin INSERT INTO [MY_TABLE] ([pk_from_other_table] ,[..] ,[
declare @count int;
set @count = 4018;
while @count <= 5040
begin
INSERT INTO [MY_TABLE]
([pk_from_other_table]
,[..]
,[...]
,[..]
,[..]
,[...]
,[...]
,[..])
select
(pk_from_other_table,
,[..]
,[...]
,[..]
,[..]
,[...]
,[...]
,[..])
@count = @count + 1;
end
但这似乎不起作用!有人能帮忙吗。。。我要做的就是插入记录数=主表中存在的记录数
??你知道我该如何做到这一点吗
我要么在计数附近得到不正确的sytax
或
Msg 102,15级,状态1,第17行
“,”附近的语法不正确。您当前的语法问题是@count=@count+1;需要设置为@count=@count+1 但是 不需要循环。您只需直接执行一个大的插入,如:
insert into your_table (fk_col, other_col1, other_col2)
select pk_col, 'something', 'something else'
from your_other_table
如果需要,可以在上面添加where子句。关于Msg 102,15级,状态1,第17行“,”附近的语法不正确:
第二个选择列表中有两个逗号:
select
(pk_from_other_table,
,[..]
移除一个
关于插入:
如果要多次将源表中的所有记录插入目标表,可以在循环中执行:
declare @count int;
set @count = 4018;
while @count <= 5040
begin
INSERT INTO DestinationTableName
(DestinationTableColumn1Name
,DestinationTableColumn2Name --ect
)
select
SourceTableColumn1Name
,SourceTableColumn2Name --ect
from SourceTableName
set @count = @count + 1;
end
您不必逐行执行此操作。请更新您的问题,我们看不到您尝试了什么。现在添加。。。添加了不正确的内容。。正在更正它,错误消息是什么?您遗漏了很多内容,包括MY_表的模式。是否有错误消息,例如,指示您无法为标识列指定值?第17行是否与您发布的简略代码有关?是的,但我想循环。。有很多这样的记录您在基于集合的环境中工作-尽可能避免循环。@user1630846-到目前为止,这不是很多记录。@user1630846循环速度慢,在使用关系数据库时应尽可能避免循环。@user1630846请参阅:
INSERT INTO DestinationTableName
(DestinationTableColumn1Name
,DestinationTableColumn2Name --ect
)
select
SourceTableColumn1Name
,SourceTableColumn2Name --ect
from SourceTableName
where SourceTablePK between 4018 and 5040 --LowerBound and UpperBound
--or SourceTablePK in (1, 2, 3) etc