4 ms·
EDIT: SEE REPLY How about (SQL Server): CREATE TABLE #P ( name VARCHAR(100), count_empty BIT NOT NULL, count INT NULL,
by infogulch 10y ago
EDIT: SEE REPLY
How about (SQL Server):
CREATE TABLE #P (
name VARCHAR(100),
count_empty BIT NOT NULL,
count INT NULL,
count_key AS ISNULL(count,0),
CHECK ((count_empty = 0 AND count IS NOT NULL) OR (count_empty = 1 AND count IS NULL)),
PRIMARY KEY (name, count_empty, count_key)
);
I think this should give the semantics you're looking for (if not the ergonomics). COUNT,SUM,AVG etc should work correctly on the "count" column (btw, I would consider using a different name ;P), and the check+primary key should enforce the constraints.
You might add a before update trigger to set count to NULL when count_empty = 1, and hiding the actual table behind a view to hide the internals of the count_key column.
- infogulch 10y agoWhoa I was way overcomplicating this. This is all you need, semantics AND ergonomics included: CREATE TABLE P ( name VARCHAR(100), count INT NULL, count_empty AS CASE WHEN count IS NULL THEN 1 ELSE 0 END, count_key AS ISNULL(count,0), PRIMARY KEY (name, count_empty, count_key) ); No trigger or updating two fields needed at all. Just update "count". If you insert NULL twice it will yell at you.