Conditional Unique index on h2 database

我们两清 提交于 2019-12-07 09:21:14

问题


I have a SAMPLE_TABLE with a column BIZ_ID which should be unique when the column active is not equal to 0.

On an oracle database the index looks like this:

  CREATE UNIQUE INDEX ACTIVE_ONLY_IDX ON SAMPLE_TABLE (CASE "ACTIVE" WHEN 0 THEN NULL ELSE "BIZ_ID" END );

How would this unique index look like on a h2 database?


回答1:


In H2, you could use a computed column that has a unique index:

create table test(
    biz_id int, 
    active int,
    biz_id_active int as 
      (case active when 0 then null else biz_id end) 
      unique
 );
 --works
 insert into test(biz_id, active) values(1, 0);
 insert into test(biz_id, active) values(1, 0);
 insert into test(biz_id, active) values(2, 1);
 --fails
 insert into test(biz_id, active) values(2, 1);


来源:https://stackoverflow.com/questions/28836704/conditional-unique-index-on-h2-database

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!