March 7, 2011 at 7:31 am
Hi, I am after a little help with an insert statement which is giving me an error of 'Subqueries are not allowed in this context. Only scalar expressions are allowed.'
I am not that clued up on scalar expressions and after hours of google search I am none the wiser.
Bascialy I am trying to insert 2 column entries into a table, incomekey and flightkey. However the income key field is defined as a char (8) not null, no auto increment has been built in. so as a work around, I am trying to do a search to find the last used number in the field and add 1 to that value hence the select MAX statement
insert into sbsincome (incomekey,flightkey) values ((select MAX(incomekey)+1 from sbsincome),116040)
If i just run the select statement without the insert it works fine. How can I get the increment value to work on my insert statement?
thank you in advance
March 7, 2011 at 7:44 am
the issue is to NOT use the INSERT...VALUES syntax, but INSERT...SELECTinstead:
insert into sbsincome (incomekey,flightkey)
select
MAX(incomekey)+ 1 AS incomekey,
116040 AS flightkey
from sbsincome
Lowell
March 7, 2011 at 7:46 am
you will need to break the logic out into seperate steps
1. define a variable to hold the value,
2. select the max(incomekey) into this variable.
3. use this variable in your insert statement
one issue you will have when using this approach for incrementing keys, is that if two or more requests are happening at the same time there will be a possibility of dupliacate keys occuring.
March 7, 2011 at 8:30 am
Thanks Lowell your example works,
I also note the warning provided by SteveB. I understand this and I am hoping this is just temporary until the company that support us can actually change the database structure.
Cheers Guys for your speedy response.
Viewing 4 posts - 1 through 3 (of 3 total)
You must be logged in to reply to this topic. Login to reply