简体   繁体   中英

INSERT INTO from tableA to tableB with count()

Inserting rows from one table to another table, I try to use a count(*) to ensure that the line_no column in table OBJ_LINES is set to 1,2,3,4.. and so on for every line added.

INSERT INTO OBJ_LINES(
id,
line_no)
SELECT (1,
(select count(*)+1 FROM OBJ_LINES WHERE id = 1)
FROM TEMPLATE_LINES tmp
WHERE tmp.id = 37;

(syntax Sybase Database) If the TEMPLATE_LINES table holds more than one row, I get a duplicate error as the count() seems to be evaluted only once, and not for every row found in the TEMPLATE_LINES table.

How may I write the sql to set 'dynamic' line_no depending on the current number of rows for a given id?

INSERT INTO OBJ_LINES(
id,
line_no)
SELECT (1,
number(*)
FROM TEMPLATE_LINES tmp
WHERE tmp.id = 37;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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