I have a simple table as scripted below.
CREATE TABLE dbo.KeyNumbers (
RowId INT IDENTITY
,ProFormaNumber NCHAR(10) NULL
,SalesOrderNumber NCHAR(10) NULL
,PurchaseOrderNumber NCHAR(10) NULL
,InvoiceCreditNoteNumber NCHAR(10) NULL
,InvoiceNumber NCHAR(10) NULL
,PurchaseInvoiceCreditNoteNumber NCHAR(10) NULL
,ModifiedDate DATETIME NULL
,CONSTRAINT PK_KeyNumbers PRIMARY KEY CLUSTERED (RowId)
) ON [PRIMARY]
The table is used to store key document numbers (Invoice number, Sales Order number etc) for the company, and as such only requires a single row. The main interaction with this table is done through stored procedures so the end use should never need to access it, but I am wondering if there is a way in SQL server to actively restrict the table to have one, and only one row, and to be able to do that at the design stage.
EDIT
Proof that Gordon's suggestion works nicely
The obvious method uses a trigger on insert to be sure the table is empty.
I've never tried this, but an index on a computed column might also work:
alter table dbo.KeyNumbers add OneAndOnly as ('OneAndOnly');
alter table dbo.KeyNumbers add constraint unq_OneAndOnly unique (OneAndOnly);
This should generate a unique key violation if a second row is inserted.
--I think this would be cleaner and utilizes the existing columns
CREATE TABLE dbo.KeyNumbers (
RowId AS (1) PERSISTED
,ProFormaNumber NCHAR(10) NULL
,SalesOrderNumber NCHAR(10) NULL
,PurchaseOrderNumber NCHAR(10) NULL
,InvoiceCreditNoteNumber NCHAR(10) NULL
,InvoiceNumber NCHAR(10) NULL
,PurchaseInvoiceCreditNoteNumber NCHAR(10) NULL
,ModifiedDate DATETIME NULL
,CONSTRAINT PK_KeyNumbers PRIMARY KEY CLUSTERED (RowId)
) ON [PRIMARY]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With