基本上我想从表中提取id
并将id
插入另一个包含其他数据的表中。所以algorythm说:
foreach id in (select id from table)
{
insert into table2 values (id,etc,etc);
}
如何使用SQL查询执行此功能?
答案 0 :(得分:6)
答案 1 :(得分:3)
insert into table2 select id,etc,etc from table;
答案 2 :(得分:0)
答案 3 :(得分:0)
在SQL Query中如果要使用循环,则使用游标Pls。检查以下样本
--DECLARE CURSOR
DECLARE @ID VARCHAR(MAX)
--READ DATA FROM TABLE TO CURSOR
DECLARE IDCR CURSOR FOR SELECT id FROM table
OPEN IDCR;
FETCH NEXT FROM IDCR INTO @ID
WHILE @@FETCH_STATUS = 0
BEGIN
INSERT INTO table2 VALUES (@ID,etc,etc)
FETCH NEXT FROM IDCR INTO @ID
END
CLOSE IDCR;
DEALLOCATE IDCR;
请查看以下参考。链接https://docs.microsoft.com/en-us/sql/t-sql/language-elements/declare-cursor-transact-sql