在插入涉及 NULL 之前检查 2 列中的重复项,SQL 服务器
Checking for duplicates in 2 columns before insert involving NULL, SQL Server
目前我有一个 table1,其中包含主键、column1 和 column2。
我的目标是,在将数据插入 table 之前检查 column1 + column2 是否唯一。
示例:
table
中的当前数据
**Primary key column1 column2**
1 1 banana
2 NULL NULL
3 2 NULL
4 1 NULL
应该成功插入以下数据:
**Primary key column1 column2**
5 1 apple
6 3 banana
7 4 NULL
应该无法插入以下数据:
**Primary key column1 column2**
8 1 banana
9 2 NULL
我会让这 2 个文件唯一,但我不能,因为我现在无法用数据填充 NULL 值。enter image description here
您可以使用 EXCEPT
运算符:
INSERT INTO table1 (column1,column2)
SELECT 1, NULL
EXCEPT
SELECT column1,column2
FROM table1 ;
您可以将 table 定义为:
create table t (
a int primary key not null,
b int,
c varchar(10),
constraint uq1 unique (b, c)
);
insert into t (a, b, c) values (1, 1, 'banana');
insert into t (a, b, c) values (2, null, null);
insert into t (a, b, c) values (3, 2, null);
insert into t (a, b, c) values (4, 1, null);
insert into t (a, b, c) values (5, 1, 'apple');
insert into t (a, b, c) values (6, 3, 'banana');
insert into t (a, b, c) values (7, 4, null);
insert into t (a, b, c) values (8, 1, 'banana'); -- fails
insert into t (a, b, c) values (9, 2, null); -- fails
请参阅 SQL<>Fiddle 中的 运行 示例。
重要说明:您在 SQL 服务器中看到的行为偏离了 SQL 标准——我什至会说这是错误的。 SQL 服务器认为 NULL
是一个真正的不同值,但它不应该;在 SQL null
中表示“存在但缺失的值,而不是没有值”。相比之下,所有其他数据库(我知道的)都将 NULL
视为非值,缺失值,无法与另一个 NULL
进行比较。因为这个异常,这个方案只在SQL服务器有效。
您可以在 table 上创建 UNIQUE CONSTRAINT。
ALTER TABLE TableName
ADD CONSTRAINT UNIQUE (column1, column2);
目前我有一个 table1,其中包含主键、column1 和 column2。 我的目标是,在将数据插入 table 之前检查 column1 + column2 是否唯一。
示例: table
中的当前数据**Primary key column1 column2**
1 1 banana
2 NULL NULL
3 2 NULL
4 1 NULL
应该成功插入以下数据:
**Primary key column1 column2**
5 1 apple
6 3 banana
7 4 NULL
应该无法插入以下数据:
**Primary key column1 column2**
8 1 banana
9 2 NULL
我会让这 2 个文件唯一,但我不能,因为我现在无法用数据填充 NULL 值。enter image description here
您可以使用 EXCEPT
运算符:
INSERT INTO table1 (column1,column2)
SELECT 1, NULL
EXCEPT
SELECT column1,column2
FROM table1 ;
您可以将 table 定义为:
create table t (
a int primary key not null,
b int,
c varchar(10),
constraint uq1 unique (b, c)
);
insert into t (a, b, c) values (1, 1, 'banana');
insert into t (a, b, c) values (2, null, null);
insert into t (a, b, c) values (3, 2, null);
insert into t (a, b, c) values (4, 1, null);
insert into t (a, b, c) values (5, 1, 'apple');
insert into t (a, b, c) values (6, 3, 'banana');
insert into t (a, b, c) values (7, 4, null);
insert into t (a, b, c) values (8, 1, 'banana'); -- fails
insert into t (a, b, c) values (9, 2, null); -- fails
请参阅 SQL<>Fiddle 中的 运行 示例。
重要说明:您在 SQL 服务器中看到的行为偏离了 SQL 标准——我什至会说这是错误的。 SQL 服务器认为 NULL
是一个真正的不同值,但它不应该;在 SQL null
中表示“存在但缺失的值,而不是没有值”。相比之下,所有其他数据库(我知道的)都将 NULL
视为非值,缺失值,无法与另一个 NULL
进行比较。因为这个异常,这个方案只在SQL服务器有效。
您可以在 table 上创建 UNIQUE CONSTRAINT。
ALTER TABLE TableName
ADD CONSTRAINT UNIQUE (column1, column2);