Domanda

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?

È stato utile?

Soluzione

INSERT INTO OBJ_LINES(
id,
line_no)
SELECT (1,
number(*)
FROM TEMPLATE_LINES tmp
WHERE tmp.id = 37;
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top