sim*_*ula -5 sql t-sql sql-server
我想在表中插入几百行,指向其他表中的pk.我一直在尝试使用while循环在表中插入多个记录.我实际上正在设置我的测试数据.
这就是我在做的事情:
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
Run Code Online (Sandbox Code Playgroud)
但这似乎不起作用!任何人都可以帮忙...我想要做的就是插入记录数=主表中存在的记录数.
?关于如何实现这个目标的任何想法?
我要么接近计数不正确的sytax
要么
消息102,级别15,状态1,行17'','附近的语法不正确.
Kla*_*sen 13
您当前的语法问题是@count = @count + 1;需要的set @count = @count + 1.
但...
不需要循环.您可以直接执行一个大插入,例如:
insert into your_table (fk_col, other_col1, other_col2)
select pk_col, 'something', 'something else'
from your_other_table
Run Code Online (Sandbox Code Playgroud)
如果需要,可以where在上面添加一个子句.
关于消息102,级别15,状态1,行17','附近的语法不正确.:
你在第二个选择列表中有双重逗号:
select
(pk_from_other_table,
,[..]
Run Code Online (Sandbox Code Playgroud)
删除一个.
关于插入:如果要将源表中的所有记录多次插入目标,可以循环执行:
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
Run Code Online (Sandbox Code Playgroud)
但是当你想要从源表到目的地插入许多行时,where就足够了:
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
Run Code Online (Sandbox Code Playgroud)
您不必逐行执行此操作.
| 归档时间: |
|
| 查看次数: |
57388 次 |
| 最近记录: |