简体   繁体   中英

Computed Column - as Primary key

I have the following Computed Column within the create table function:

Create table test
(
Code1 nchar(10),
Code2 nchar (10),
Type nchar(10),
Final AS CASE WHEN LEN(Code1)>0 THEN Code1 WHEN LEN(Code2)>0 THEN Code2 ELSE Type END
);

Alter table test
add constraint PK_Test1
Primary Key (Final)

But I am getting the following error

"Cannot define PRIMARY KEY constraint on nullable column in table".

This is because Code 1, Code 2 and Type can be NULL, but all the three will never be NULL. One of them will always have a value.

Is there anyway I can get define the computed column as a primary key with the above in mind?

Many thanks - JT

Your computed column needs to be persisted and NOT NULL to be used as a primary key;

Create table test
(
    Code1 nchar(10),
    Code2 nchar (10),
    Type nchar(10),
    Final AS CASE WHEN LEN(Code1)>0 THEN Code1 
                  WHEN LEN(Code2)>0 THEN Code2 
                  ELSE Type END 
          PERSISTED NOT NULL
);

An SQLfiddle to test with .

Why not just use a unique constraint as it will allow null

Unlike PRIMARY KEY constraints, UNIQUE constraints allow for the value NULL. However, as with any value participating in a UNIQUE constraint, only one null value is allowed per column. A UNIQUE constraint can be referenced by a FOREIGN KEY constraint.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM