Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to restrict a sql table to only have a single row at the design stage

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

enter image description here

like image 606
Dom Sinclair Avatar asked Mar 19 '16 17:03

Dom Sinclair


2 Answers

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.

like image 69
Gordon Linoff Avatar answered Sep 29 '22 15:09

Gordon Linoff


--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]
like image 37
Vincent Avatar answered Sep 29 '22 14:09

Vincent