在Oracle SQL中创建1000行的查询

时间:2017-11-16 12:39:57

标签: sql oracle

我正在尝试编写一个查询来生成1000行,我有一个名为CCHOMEWORK的表,包含2列,ID整数(PK)和StudentID varchar,其中包含所有1000行的值。

我尝试了这个,但我一直收到错误并且无法正常工作

SET @MyCounter = 1

WHILE @MyCounter < 1000

BEGIN

INSERT INTO CCHOMEWORK
    (ID)
VALUES
    @MyCounter)

    set @MyCounter = @MyCounter + 1;

END

2 个答案:

答案 0 :(得分:4)

这将创建1000行:

SELECT LEVEL
FROM   DUAL
CONNECT BY LEVEL <= 1000

您可以将其包含在插入内容中:

INSERT INTO CCHOMEWORK (ID)
SELECT LEVEL
FROM   DUAL
CONNECT BY LEVEL <= 1000

但是,如果要插入多个顺序ID,可能最好使用序列:

CREATE SEQUENCE CCHOMEWORK__ID__SEQ
/

然后:

INSERT INTO CCHOMEWORK (ID)
SELECT CC_HOMEWORK__ID__SEQ.NEXTVAL
FROM DUAL
CONNECT BY LEVEL <= 1000;

或者:

BEGIN
  FOR i IN 1 .. 1000 LOOP
    INSERT INTO CCHOMEWORK (ID) VALUES ( CC_HOMEWORK__ID__SEQ.NEXTVAL );
  END LOOP;
END;
/

答案 1 :(得分:0)

Oracle数据库语法(使用PL / SQL):

DECLARE 
    MyCounter NUMBER := 1;
BEGIN
    LOOP
        EXIT WHEN MyCounter> 1000;
        INSERT INTO CCHOMEWORK (ID)
        VALUES(MyCounter);
        MyCounter := MyCounter+1;
    END LOOP;
    COMMIT;
END;
/