【INSERT】在INSERT插入语句中引入条件限制选项实现数据插入控制

  Oracle的insert插入语句的功能很是强大,我们可以实现在插入的过程中仅允许插入指定的数据记录,功能展示在此,供参考。

1.环境准备
1)创建T表
sec@ora10g> create table t (x number, y number);

Table created.

2)初始化两条数据,用于后续插入语句比对
sec@ora10g> insert into t values (1,null);

1 row created.

sec@ora10g> insert into t values (2,2000);

1 row created.

sec@ora10g> select * from t;

         X          Y
---------- ----------
         1
         2       2000

2.尝试使用带限制条件的插入语句
1)以下两条SQL插入语句是符合条件的例子
这里我们使用的是“with check option”选项限制插入T表时Y列值只允许是3000或4000。
sec@ora10g> insert into (select * from t where y in (3000,4000) with check option) values(3,3000);

1 row created.

sec@ora10g> insert into (select * from t where y in (3000,4000) with check option) values(4,4000);

1 row created.

sec@ora10g> select * from t;

         X          Y
---------- ----------
         1
         2       2000
         3       3000
         4       4000

上面两条数据符合插入条件,插入成功。

2)尝试插入不符合条件的数据
sec@ora10g> insert into (select * from t where y in (3000,4000) with check option) values(5,5000);
insert into (select * from t where y in (3000,4000) with check option) values(5,5000)
*
ERROR at line 1:
ORA-01402: view WITH CHECK OPTION where-clause violation

sec@ora10g> select * from t;

         X          Y
---------- ----------
         1
         2       2000
         3       3000
         4       4000

显然,在这种约束条件下,我们是无法插入Y值不等于3000和4000的数据的。

3)去掉“with check option”选项再次尝试数据插入
sec@ora10g> insert into (select * from t where y in (3000,4000)) values(5,5000);

1 row created.

sec@ora10g> select * from t;

         X          Y
---------- ----------
         1
         2       2000
         3       3000
         4       4000
         5       5000

此时插入数据的约束已取消。数据可以成功插入到T表中。

3.小结
  本文给出了一种插入数据的特殊用法,目的是提醒大家,我们在使用常规插入技术的同时还有很多新奇的方法值得探索。

Good luck.

secooler
11.09.05

-- The End --

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/519536/viewspace-706706/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/519536/viewspace-706706/

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值