Autoincrement varchar column optionally - sql

I have a table with guid identifier and one field that is a 5 characters string that can be specified by user, but it is optional, and it should be unique per user. I'm looking for a way to have this field always there, even if user doesn't specify it. The easiest approach is to have it like "00001", "00002"... etc. in case that user doesn't specify it, it is stored like this. I'm using SQL and entity framework core. What is the best way to achieve this?
EDIT: maybe trigger that will check after insert if that field is not specified and then just take current row number and convert it to string? does this make sense?
Cheers

Setting a default value to '00001' can be done define the field with:
NOT NULL DEFAULT right('0000' || to_char(SomeSequence.nextval),5) (pseudo-code to be adapted to the DBMS you are connected to).
Compared to the solution in your EDIT, this will at least guarantee that 2 inserts at the same time from 2 different users get assigned different values.
The real problem comes with the unique constraint on the column. This does not work nicely when mixing manual input with calculated values.
If as a user, I input (manually) 00005, then the insertion will fail when SomeSequence reaches 5.
I think this problem will exist regardless of how you implement the generation of values (sequence, trigger, external code, ...)
Even if you are fine with coding some additional (and probably complicated) logic to manage that, it will probably decrease concurrency.

Related

SQL/EF Applying defaultvalue to entries that cannot be null any longer

We added a new column in a migration, and then need to modify it to no longer be nullable. The entries are null, however.
Is there a way to apply default value as part of the migration, to entries where the value is null?
Or is the best solution simply to run a stored procedure, or otherwise manually edit the fields to be something valid?
ps. Did the later, because i'm a student, needed it working now, and it was just 8 entries, but i'm still curious.
DavidG's response is pretty much what I did in a testbed, and it works perfectly well.

'-999' used for all condition

I have a sample of a stored procedure like this (from my previous working experience):
Select * from table where (id=#id or id='-999')
Based on my understanding on this query, the '-999' is used to avoid exception when no value is transferred from users. So far in my research, I have not found its usage on the internet and other company implementations.
#id is transferred from user.
Any help will be appreciated in providing some links related to it.
I'd like to add my two guesses on this, although please note that to my disadvantage, I'm one of the very youngest in the field, so this is not coming from that much of history or experience.
Also, please note that for any reason anybody provides you, you might not be able to confirm it 100%. Your oven might just not have any leftover evidence in and of itself.
Now, per another question I read before, extreme integers were used in some systems to denote missing values, since text and NULL weren't options at those systems. Say I'm looking for ID#84, and I cannot find it in the table:
Not Found Is Unlikely:
Perhaps in some systems it's far more likely that a record exists with a missing/incorrect ID, than to not be existing at all? Hence, when no match is found, designers preferred all records without valid IDs to be returned?
This however has a few problems. First, depending on the design, user might not recognize the results are a set of records with missing IDs, especially if only one was returned. Second, current query poses a problem as it will always return the missing ID records in addition to the normal matches. Perhaps they relied on ORDERing to ease readability?
Exception Above SQL:
AFAIK, SQL is fine with a zero-row result, but maybe whatever thing that calls/used to call it wasn't as robust, and something goes wrong (hard exception, soft UI bug, etc.) when zero rows are returned? Perhaps then, this ID represented a dummy row (e.g. blanks and zeroes) to keep things running.
Then again, this also suffers from the same arguments above regarding "record is always outputted" and ORDER, with the added possibility that the SQL-caller might have dedicated logic to when the -999 record is the only record returned, which I doubt was the most practical approach even in whatever era this was done at.
... the more I type, the more I think this is the oven, and only the great grandmother can explain this to us.
If you want to avoid exception when no value transferred from user, in your stored procedure declare parameter as null. Like #id int = null
for instance :
CREATE PROCEDURE [dbo].[TableCheck]
#id int = null
AS
BEGIN
Select * from table where (id=#id)
END
Now you can execute it in either ways :
exec [dbo].[TableCheck] 2 or exec [dbo].[TableCheck]
Remember, it's a separate thing if you want to return whole table when your input parameter is null.
To answer your id = -999 condition, I tried it your way. It doesn't prevent any exception

Database-table default value for a column in SAP R/3

In the context of my SAP Application I added a column to an existing table and would like to define a default value for it, so that old code working with the table (code that is inserting lines especially) doesn't have to care about the new column - rather I want it to be filled with a predefined default value automatically (only if no value is specified of course).
The DB-system that lies behind is an Oracle-DB, though I have only access to it through the SAP-GUI and the ABAP-SQL.
As our company expert for SAP did not know if this is possible I thought maybe someone here would. So - is this possible and if it is - how?
Edit - Requested Scenario details:
The scenario is actually very simple: We have a users-table for our application containing the standard user stuff (name, some setting, Ids, division, a bunch of flags and so on), and I added a column to store a simple setting (the design the user has chosen for his webinterface). It contains simply a name (char 40). That's the column I talked about above and I want the default value for it to be let's say "Default Design".
Please, don't even think about doing this on a database level. Seriously. Changes made to the database layer directly will not be visible inside the system and lead to all kinds of strange side effects that will be a nightmare to support. Besides, your changes won't be picked up by the Change and Transport System - you'd have to update the QA and Production systems manually.
If possible, I'd recommend to choose your domain values in a way that the neutral field value (spaces, zero, whatever) corresponds to your default value. If this is not possible, please describe your scenario in detail to get a more specific answer.
The SAP R/3 / ABAP environment does not give you the option of adding default values for a column. You can only choose to force the system to fill the non-NULL default values when adding a column, but this is usually a bad idea. It takes time to modify all the data and insert the default values, and depending on the table size and criticality, this can lead to a production outage. Filling the fields with default values has to be performed by the application server, not the database. In your case, I'd just add the logic in the read-access module, something like
IF my_user-ze_design IS INITIAL.
my_user-ze_design = co_ze_default_design.
ENDIF.
You can define default values for columns added to tables - and if your DB is Oracle 11g (or later), Oracle introduced "Dictionary Only Add Column", which means the default value metadata is stored only in the dictionary - so existing records do not need to be updated with the default value and there is no overhead, no matter how large the table.

Update computed column, convert VARCHAR to BIT

Currently I have a database that stores boolean fields as VARCHAR(1) ('T' or 'F'). I want to replace these with BIT. The problem is that this would require a ton of changes in the program that uses the database. So I thought the logical step is to add a BIT field and replace the existing VARCHAR(1) field with a computed column that I access rather than accessing the BIT field (thus the program can continue to work as is without changes, and be changed to use the BIT field over time).
I know this won't work (UPDATE and INSERT doesn't work on computed columns). I know one option is to rename the existing table and add a view through which to access it, but I don't see that as a viable solution, as adding and removing columns, changing dependent views, etc. would be prone to errors (and it's not a neat solution in my opinion).
My question is - what are my options to achieve the above behaviour (such that the program can continue working as is)?
An example:
User (Active VARCHAR(1), ...)
Changed to use computed columns: (won't work)
User (Active_B BIT, Active AS CASE Active_B WHEN 1 THEN 'T' ELSE 'F' END, ...)
UPDATE: Fixed error in example.
It would have to be:
ALTER TABLE dbo.User
ADD Active AS CASE Active_B WHEN 1 THEN 'T' ELSE 'F' END PERSISTED
You need to use the column name (not the datatype) in the CASE. And I'd recommend making the computed column persisted, too - so that the value gets actually stored on disk (and not recomputed every time you access it).
An option is to have both a VARCHAR and a BIT field and use triggers to update between them.
I'll just have to figure out how to prevent infinite recursion (one idea is to have a field that serves no other purpose than to check if this trigger resulted from an update within another trigger (check if we're updating it and include it in the update in the trigger)). The updates need to go both ways to allow for easy backward compatibility.

Positive or negative boolean field names

A table's boolean fields can be named using the positive vs the negative...
for example, calling a field:
"ACTIVE" , 1=on / 0=off
or
"INACTIVE" , 0=on / 1=off
Question:
Is there a proper way to make this type of table design decision, or is it arbitrary?
My specific example is a messages table with a bool field (private/public). This field will be set using a form checkbox when a user enters a new message. Is there a benefit in naming the field "public" vs "private"?
thanks.
I always prefer positive names, to avoid double negatives in code. "Is not inactive" is often cause for a double take when reading. "Is inactive" can always be written as "if (!Active)" whilst taking advantage of built-in language semantics.
My personal preference:
Use prefixes like "Is", "Has", etc. for Boolean fields to make their purpose clear.
Always name variables in the affirmative. For Active/Inactive, I would name it IsActive.
Don't make a bit field nullable unless you really have a specific purpose in doing so.
In your specific use case, the field should be named either IsPublic or IsPrivate--whichever name would result in a True answer when the user ticks the checkbox.
i would not disagree with some of the other answers but definitely avoid the incorrect answer which is not to put in double negatives always
Always use positive names.
If use negative names, you very quickly get into double negation. Not that double negation is rocket surgery, but it's a brain cycle and those are valuable :)
Always use positive.
It's simpler.
Take using the negation to the logical extreme: if InActive is better than Active, then why not InInActive, or InInInActive?
Because it would be less simple.
The proper way to handle these situations is to create a table to house the values associated with the column, and create a foreign key relationship between the two tables. IE:
WIDGETS table:
WIDGET_ID
WIDGET_STATUS (fk)
WIDGET_STATUS_CODES table:
WIDGET_STATUS_CODE (pk)
DESCRIPTION
If possible, WIDGET_STATUS_CODE would be a natural key (IE: ACT for "Active", INA for "Inactive"). This would make records more human readable, but isn't always possible so you'd use an artificial/surrogate key (like an auto-number/sequence/etc).
You want to do this because:
It's readable what status indicates (which was the original question)
Future proof in the need to define/use more statuses
Provides referencial integrity so someone couldn't set the value to 2, 3, 4, etc.
Space is cheap; there's nothing efficient about allowing bad data
Try to avoid boolean fields in databases alltogether.
One, the RM has a much better way to represent truth-valued information than via boolean fields : via the presence of a tuple in a table.
Two, boolean fields are very bad discriminators when querying. It's virtually complete madness to index them, so when querying, the presence of boolean fields gives no benefit at all.