Quantcast
Channel: CodeSection,代码区,SQL Server(mssql)数据库 技术分享 - CodeSec
Viewing all articles
Browse latest Browse all 3160

Restricting the sql server table to two fields

$
0
0

I have a table with multiple columns with data periodically inserted. I would like to focus on two fields where if one value is entered in Column A, nothing should be allowed to be entered in column B. Hope this makes sense; I will illustrate below:

TABLE TEST COLUMN a COLUMN b COLUMN c DATEADDED INSERT INTO TEST(COLUMN A, COLUMN B) VALUE('HELLO','HELLO')

This should not be allowed to occur but rather a null value should be in either one. Basically a constraint to restrict one value being in either column for a given record.

Please check the Check Contraint at http://www.w3schools.com/sql/sql_check.asp

In your case you can do do the following:

CREATE TABLE Persons ( a VARCHAR(255) NULL, b VARCHAR(255) NULL, c VARCHAR(255) NULL, DATEADDED DATETIME DEFAULT CURRENT_TIMESTAMP, CONSTRAINT chk_AtLeastOneNull CHECK (A IS NULL OR B IS NULL) )

and in the insert if you do

insert into Persons(a,b,c) values ('a', 'b', null)

you'll get the error

Msg 547, Level 16, State 0, Line 1 The INSERT statement conflicted with the CHECK constraint "chk_AtLeastOneNull". The conflict occurred in database "databasename", table "dbo.Persons". The statement has been terminated.

You can combine other expressions in the check, for instance:

CONSTRAINT chk_AtLeastOneNull CHECK (A IS NULL OR (A IS NOT NULL AND B IS NULL))


Viewing all articles
Browse latest Browse all 3160

Trending Articles