I have MSSQL table having columns, serves as storage for items for user with certain name. Each user have one record in table Items that looks like that:
Name(string) 1(string) 2(string) 3(string) 4(string) 5(string)
When inserting data, I would need to use the column (“packet”) ona by one. Meaning if “1” contains data, use column “2”. If “1” is empty, use “1”. If only “3” is empty, use “3”/
In other words, I always need to select the lowest empty column to write the data in. If none of these 5 is empty, then do not write data at all.
Could anyone help me with that query? Thank you
The correct way to model this in SQL would be:
You could then write your insert as:
where
@Nameand@Valueare the supplied values to insert. If there are already 5 items in the table for a particular name, you’ll get a check constraint error and the insert will fail.This also makes querying for particular values possible, without having to search 5 different columns, and it means that extending to more items in the future far easier (by just changing the check constraint)
I’d had the impression that this was insert only. If deletions are occurring, and you want to reuse items, then the insert query would be:
which will now fail because of a not-null constraint once you’re up at 5 items. It could be simpler if you already have a numbers table in your database, but I’ve assumed not above.