简体   繁体   English

使用每一行作为 Insert Into 循环遍历表的行 - SQL

[英]Looping through rows of a table using each row as Insert Into - SQL

I have a table called Reviews, and I don't think the contents of this matter too much for the question, but I want to go through each row of this table, one by one, using the data in each row as part of an Insert Into statement.我有一个叫做Reviews的表,我觉得这个问题的内容并没有太大的问题,但是我想go通过这个表的每一行,一个接一个,使用每一行中的数据作为一个插入到语句。 As part of each row being used, I need to increment an integer (called Evid) by 1 because that integer needs to be used as part of the Insert Into statement.作为正在使用的每一行的一部分,我需要将 integer(称为 Evid)增加 1,因为 integer 需要用作 Insert Into 语句的一部分。 So the first row will have 1, the second row will have 2 etc.所以第一行将有 1,第二行将有 2,依此类推。

I am using Advantage Architect, and a rough idea of how I see this working is below, which I know I need help on.我正在使用 Advantage Architect,下面是我如何看待这个工作的粗略想法,我知道我需要帮助。

Row example of the table I want to use to loop through:我想用来循环的表的行示例:

IDENT|REFERENCE|TITLE
1234 | TEST    | testing 
4456 | TEST2   | testing2 

And I want to insert into another table, where it'll look like this.我想插入另一个表,它看起来像这样。 Each row it runs through from the above will be used to insert more than one row into the below table, but keeping the EVID as the sequential INTEGER value.它从上面运行的每一行将用于在下表中插入多行,但将 EVID 保持为顺序 INTEGER 值。

IDENT|REFERENCE|TITLE    |STAFF |EVID
1234 | TEST    | testing |STAFF1| 1
1234 | TEST    | testing |STAFF2| 1
4456 | TEST2   | testing2|STAFF1| 2
4456 | TEST2   | testing2|STAFF2| 2

_ _

declare evid integer;
declare cur cursor;

evid = 1;

open cur

//Do Insert Into
//Evid +1;
Close cur;

The relevant information on using cursor can be found in online help使用cursor的相关信息可以在在线帮助中找到

Modifying the sample code for your problem:针对您的问题修改示例代码:

DECLARE @evid Integer;
DECLARE cur CURSOR;    

OPEN cur As SELECT * FROM sourceTable;

@evid = 1;


WHILE FETCH cur DO
    INSERT INTO destination (IDENT, REFERENCE, TITLE, STAFF, EVID)
        VALUES (cur.IDENT, cur.REFERENCE, cur.TITLE, 'STAFF1', @evid);
    INSERT INTO destination (IDENT, REFERENCE, TITLE, STAFF, EVID)
        VALUES (cur.IDENT, cur.REFERENCE, cur.TITLE, 'STAFF2', @evid);

    @evid = @evid + 1;
END WHILE;


CLOSE cursor1;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM