如何保证 insert 唯一?
本帖最后由 rainxies 于 2013-09-27 11:27:00 编辑 假设有这样一个案例:
公司A给每个新员工都发门禁卡,其表结构为:
工号 卡号 离职日期
小王 1234 2013-02-01
张三 1234 2013-12-31
李四 ????
现在的要求是,要保证还未离职员工的卡号不能相同!
如上样例数据,小王已离职,其卡号可以给张三用
但是张三还未离职,他的卡号就不能给李四
那么现在的问题是,如何通过程序来保证上述规则?要考虑到多个人同时insert同一个卡号的情况
本来想用
select 卡号 from 门禁卡 where 卡号='1234' for update
CASE WHEN 离职日期 IS NULL or 离职日期>sysdate THEN 卡号 END
insert into t1 (id,card,trndate)
select 'ID3','C1',null from dual where not exists(select 1 from t1 where card='C1' and (trndate is null or trndate>sysdate))
;