Question : Using subquery to supply VALUE in INSERT statement

Hi Guys,
I am trying to construct an INSERT SQL statement with a subquery used to return one of the values to be inserted:

INSERT INTO tb_OrderLines ( Order_ID, Line_No, Part_No, Qty )
VALUES( 'A0001', (SELECT MAX(Line_No) + 1 as NextLineNo FROM tb_OrderLines WHERE Order_ID = 'A0001'), 'B34566', '6');

The other fields to be inserted have literal values.

For the second field I am using a SELECT query to dynamically calculate what the next line number should be.

Sample Data
Order_ID      Line_No      Part_No      Qty
A0001      1      B5641      2
A0001      2      B1121      1

So in my INSERT query above I am try to insert a new record for Order_ID A0001 but I want the SQL to dynamically work out that the next line number is 3 and this value should be inserted with the new record in the Line_No field.


Cheers


B Cunney

Answer : Using subquery to supply VALUE in INSERT statement

j.i.c. use nz

SELECT  'A0001',MAX(nz(LineNo,0)) + 1  incase A0001 is not found  

Ed.
Random Solutions  
 
programming4us programming4us