我在创建表函数中有以下计算列:
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)
但我收到以下错误
"Cannot define PRIMARY KEY constraint on nullable column in table".
这是因为Code 1、Code 2和Type可以为NULL,但三者永远不会为NULL。其中之一将始终具有值。
考虑到上述情况,我是否可以将计算列定义为主键?
非常感谢 - JT
最佳答案
您的计算列需要持久化并且 NOT NULL 才能用作主键;
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
);
关于tsql - 计算列 - 作为主键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35064253/