Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Server: how to constrain a table to contain a single row?

I want to store a single row in a configuration table for my application. I would like to enforce that this table can contain only one row.

What is the simplest way to enforce the single row constraint ?

like image 929
Martin Avatar asked Oct 19 '10 10:10

Martin


People also ask

How do I limit rows in SQL Server?

If you don't need to omit any rows, you can use SQL Server's TOP clause to limit the rows returned. It is placed immediately after SELECT. The TOP keyword is followed by integer indicating the number of rows to return. In our example, we ordered by price and then limited the returned rows to 3.

How do I get only one row in SQL Server?

While the table name is selected type CTRL + 3 and you will notice that the query will run and will return a single row as a resultset. Now developer just has to select the table name and click on CTRL + 3 or your preferred shortcut key and you will be able to see a single row from your table.

How can constraint a table in SQL Server?

Use the view table_constraints in the information_schema schema. The column table_name gives you the name of the table in which the constraint is defined, and the column constraint_name contains the name of the constraint.

How do you constraint a table?

SQL constraints are used to specify rules for the data in a table. Constraints are used to limit the type of data that can go into a table. This ensures the accuracy and reliability of the data in the table. If there is any violation between the constraint and the data action, the action is aborted.


1 Answers

You make sure one of the columns can only contain one value, and then make that the primary key (or apply a uniqueness constraint).

CREATE TABLE T1(     Lock char(1) not null,     /* Other columns */,     constraint PK_T1 PRIMARY KEY (Lock),     constraint CK_T1_Locked CHECK (Lock='X') ) 

I have a number of these tables in various databases, mostly for storing config. It's a lot nicer knowing that, if the config item should be an int, you'll only ever read an int from the DB.

like image 55
Damien_The_Unbeliever Avatar answered Sep 20 '22 22:09

Damien_The_Unbeliever