# Check the database for an order number

This code will check the database for an order number. If none exist it creates one. If one does exist then it will increment it by one and update the database. Is this the most efficient way to handle this?

// Order Number check
let updateOrderNumber bizLocId =

// order number record exist
let numExist =
query{
for row in tool.db.Order_Order_OrderNumber do
count
}

// retrieve number
if numExist < 1 then
let firstOrder =
dbSchema.ServiceTypes.Order_Order_OrderNumber(
OrderNumber = 1
)
// save to db
tool.insertRowIn tool.db.Order_Order_OrderNumber firstOrder
tool.saveToDb ()
1
else
let numRecord =
query{
for row in tool.db.Order_Order_OrderNumber do
select row
exactlyOneOrDefault
}
// update order number in db
let newOrderNumber =
numRecord.OrderNumber + 1
numRecord.OrderNumber <- newOrderNumber
tool.saveToDb ()

newOrderNumber

• I think you need to use transactions here. Otherwise, two instances of this running at the same time could create the same ID. – svick Jun 18 '14 at 18:05
• @svick Can you provide an example? I'm new to F#. – user1206480 Jun 18 '14 at 18:09
• @user1206480 if your database supports it, you should use an auto-incrementing identity column for this rather than implementing it in code. Then, you would only have to insert new rows with the appropriate BusinessLocationId, and the OrderNumber would automatically generate for you. – Dan Lyons Jul 28 '14 at 18:06