两列中的唯一值

时间:2015-11-13 17:15:23

标签: sql-server tsql

我有两列,我需要它们彼此之间是唯一的(就像它是1列)。

我的第一次尝试是创建序列并设置默认约束。

create sequence seq1
    as bigint
    start with 1
    increment by 1
    cache;
go

create table product (
    pk uniqueidentifier
    , id_1 bigint not null default (next value for seq1)
    , id_2 bigint not null default (next value for seq1)
);
go

insert into product (pk) values (newid());
insert into product (pk) values (newid());
insert into product (pk) values (newid());
insert into product (pk) values (newid());
insert into product (pk) values (newid());
go

它不起作用。上面查询的结果将是:

id_1  id_2
 1     1
 2     2
 3     3
 4     4
 5     5

目前我停止使用偶数而非偶数的2个序列。

create sequence seq2
    as bigint
    start with 1
    increment by 2
    cache;
go

create sequence seq3
    as bigint
    start with 2
    increment by 2
    cache;
go

但是如果将来我需要添加另一个也必须是唯一的列我会遇到问题。

我也考虑过存储过程。这样的事情对我有用。

create procedure sp_insertProduct
as
begin
    declare @id1 as bigint = next value for seq1;
    declare @id2 as bigint = next value for seq1;
    insert into product (pk, id_1, id_2) values (newid(), @id1, @id2);
end
go

exec sp_insertProduct;
exec sp_insertProduct;
exec sp_insertProduct;
go

但是由于我的ORM框架功能,我无法使用存储过程进行插入。

对于这个问题,还有更好的解决方案吗?

PS。由于某些原因,我不能使用uniqueidentifiers。

更新 我想我需要清楚地解释一下问题。我现在有一个可行的解决方案(目前的答案也都有效),但我想知道是否有可扩展的解决方案:

  1. 在多列中提供值的唯一性(具有 将来添加其他列。)
  2. 避免使用uniqueidentifiers
  3. 为了更好地理解问题,这就是我检查唯一性的方法:

    with src as (
        select id_1 as id from product
        union all
        select id_2 as id from product
    )
    select id, count(*) as equal_values
    from src
    group by id
    having (count(*) > 1)
    

2 个答案:

答案 0 :(得分:1)

create sequence seq1
    as bigint
    start with 1
    increment by 2
    cache;
go

create table product (
    pk uniqueidentifier
    , id_1 bigint not null default (next value for seq1)
    , id_2 bigint not null default (next value for seq1 + 1)
);
go

这样做..

insert into product (pk) values (newid());
insert into product (pk) values (newid());
insert into product (pk) values (newid());
insert into product (pk) values (newid());
insert into product (pk) values (newid());

这会产生..

pk                                      id_1  id_2
2A159914-8105-4DC1-9D7E-570CC5444172    1     2
6DAFEF16-2B81-4A10-99EF-B3F1A74389C6    3     4
8C6F6697-D993-4320-92BB-04CD56804C5A    5     6
AC97F37F-CAC3-4E83-BDD4-4B55D009C334    7     8
3DDAADA0-D7DB-4350-8087-ABF02B539552    9     10

SQL Fiddle

答案 1 :(得分:0)

可能这看起来很天真,但应该有效。我没有检查,但你可能需要添加一些括号:

create table product (
    pk uniqueidentifier
    , id_1 bigint not null default (next value for seq1)
    , id_2 bigint not null default (-next value for seq1)
);
go
相关问题